@ddt-tools/cli 0.2.0 → 0.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/advise-tests-YNMKVJCD.js +87 -0
- package/dist/advise-tests-YNMKVJCD.js.map +1 -0
- package/dist/ai-NTNPYEKZ.js +86 -0
- package/dist/ai-NTNPYEKZ.js.map +1 -0
- package/dist/anonymize-LERTWUQO.js +139 -0
- package/dist/anonymize-LERTWUQO.js.map +1 -0
- package/dist/approval-GGZGKIU4.js +73 -0
- package/dist/approval-GGZGKIU4.js.map +1 -0
- package/dist/approval-chain-GWJKZHVU.js +118 -0
- package/dist/approval-chain-GWJKZHVU.js.map +1 -0
- package/dist/audit-log-2PH55BU4.js +159 -0
- package/dist/audit-log-2PH55BU4.js.map +1 -0
- package/dist/backlog-QNXGOUF4.js +76 -0
- package/dist/backlog-QNXGOUF4.js.map +1 -0
- package/dist/bisect-W3XKKRWG.js +111 -0
- package/dist/bisect-W3XKKRWG.js.map +1 -0
- package/dist/bookmarks-XVOGXGMC.js +107 -0
- package/dist/bookmarks-XVOGXGMC.js.map +1 -0
- package/dist/branch-S3I2IJGQ.js +103 -0
- package/dist/branch-S3I2IJGQ.js.map +1 -0
- package/dist/build-MP3JQEFO.js +20 -0
- package/dist/build-MP3JQEFO.js.map +1 -0
- package/dist/catalog-3J3NFNXP.js +137 -0
- package/dist/catalog-3J3NFNXP.js.map +1 -0
- package/dist/changelog-ZQAH3ULB.js +216 -0
- package/dist/changelog-ZQAH3ULB.js.map +1 -0
- package/dist/chunk-2FT6HXKS.js +55 -0
- package/dist/chunk-2FT6HXKS.js.map +1 -0
- package/dist/chunk-DGUM43GV.js +11 -0
- package/dist/chunk-DGUM43GV.js.map +1 -0
- package/dist/chunk-DL3V7UJ2.js +25 -0
- package/dist/chunk-DL3V7UJ2.js.map +1 -0
- package/dist/chunk-VM2H4LAO.js +15 -0
- package/dist/chunk-VM2H4LAO.js.map +1 -0
- package/dist/chunk-XFXG347C.js +40 -0
- package/dist/chunk-XFXG347C.js.map +1 -0
- package/dist/cli.js +499 -19402
- package/dist/cli.js.map +1 -1
- package/dist/compare-P7JOV76O.js +379 -0
- package/dist/compare-P7JOV76O.js.map +1 -0
- package/dist/compare-profiles-H33CXZPD.js +219 -0
- package/dist/compare-profiles-H33CXZPD.js.map +1 -0
- package/dist/completion-ZSNCQKJ2.js +89 -0
- package/dist/completion-ZSNCQKJ2.js.map +1 -0
- package/dist/connection-CDGVEFUC.js +148 -0
- package/dist/connection-CDGVEFUC.js.map +1 -0
- package/dist/cost-estimate-S2MKHT2H.js +321 -0
- package/dist/cost-estimate-S2MKHT2H.js.map +1 -0
- package/dist/data-compare-46ZI7KHL.js +128 -0
- package/dist/data-compare-46ZI7KHL.js.map +1 -0
- package/dist/data-fit-WGEPLD5S.js +127 -0
- package/dist/data-fit-WGEPLD5S.js.map +1 -0
- package/dist/deploy-status-4H5KJFRC.js +58 -0
- package/dist/deploy-status-4H5KJFRC.js.map +1 -0
- package/dist/design-ILX3ZSWW.js +135 -0
- package/dist/design-ILX3ZSWW.js.map +1 -0
- package/dist/diagnose-WPUL67E4.js +150 -0
- package/dist/diagnose-WPUL67E4.js.map +1 -0
- package/dist/discover-DEO2R5T6.js +78 -0
- package/dist/discover-DEO2R5T6.js.map +1 -0
- package/dist/docs-QNY3MUVO.js +183 -0
- package/dist/docs-QNY3MUVO.js.map +1 -0
- package/dist/drift-FDRNPWQA.js +233 -0
- package/dist/drift-FDRNPWQA.js.map +1 -0
- package/dist/drift-gate-6BWWWMHW.js +103 -0
- package/dist/drift-gate-6BWWWMHW.js.map +1 -0
- package/dist/error-lookup-4R3Y4RBC.js +56 -0
- package/dist/error-lookup-4R3Y4RBC.js.map +1 -0
- package/dist/errorReporting-3LPE2IJY.js +109 -0
- package/dist/errorReporting-3LPE2IJY.js.map +1 -0
- package/dist/exec-JOLH5LPT.js +122 -0
- package/dist/exec-JOLH5LPT.js.map +1 -0
- package/dist/explain-NS26WE2Y.js +189 -0
- package/dist/explain-NS26WE2Y.js.map +1 -0
- package/dist/explorer-GSYYYOAL.js +58 -0
- package/dist/explorer-GSYYYOAL.js.map +1 -0
- package/dist/extract-4LWEZG4O.js +152 -0
- package/dist/extract-4LWEZG4O.js.map +1 -0
- package/dist/features-KQV4OFIZ.js +54 -0
- package/dist/features-KQV4OFIZ.js.map +1 -0
- package/dist/feedback-CBLGXUEG.js +158 -0
- package/dist/feedback-CBLGXUEG.js.map +1 -0
- package/dist/find-SMXRCZ76.js +176 -0
- package/dist/find-SMXRCZ76.js.map +1 -0
- package/dist/format-HMGG6MY3.js +277 -0
- package/dist/format-HMGG6MY3.js.map +1 -0
- package/dist/generate-W7VLBDLI.js +160 -0
- package/dist/generate-W7VLBDLI.js.map +1 -0
- package/dist/graph-YYL5UYCJ.js +168 -0
- package/dist/graph-YYL5UYCJ.js.map +1 -0
- package/dist/history-GDRFP4PG.js +184 -0
- package/dist/history-GDRFP4PG.js.map +1 -0
- package/dist/hosts-DRFZTMIJ.js +45 -0
- package/dist/hosts-DRFZTMIJ.js.map +1 -0
- package/dist/impact-A4NU6CB2.js +63 -0
- package/dist/impact-A4NU6CB2.js.map +1 -0
- package/dist/import-2RNYDL4E.js +79 -0
- package/dist/import-2RNYDL4E.js.map +1 -0
- package/dist/index.cjs +11 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +8 -2
- package/dist/index.js.map +1 -1
- package/dist/init-EAOGNGXI.js +54 -0
- package/dist/init-EAOGNGXI.js.map +1 -0
- package/dist/install-hooks-G3Y5LVXK.js +109 -0
- package/dist/install-hooks-G3Y5LVXK.js.map +1 -0
- package/dist/license-Z5YSC7XQ.js +43 -0
- package/dist/license-Z5YSC7XQ.js.map +1 -0
- package/dist/lineage-C5CGVP36.js +555 -0
- package/dist/lineage-C5CGVP36.js.map +1 -0
- package/dist/lint-AQFPZ3WG.js +144 -0
- package/dist/lint-AQFPZ3WG.js.map +1 -0
- package/dist/mcp-F7FND5X7.js +343 -0
- package/dist/mcp-F7FND5X7.js.map +1 -0
- package/dist/migrate-from-dbt-K4ELOWUD.js +156 -0
- package/dist/migrate-from-dbt-K4ELOWUD.js.map +1 -0
- package/dist/migrate-platform-E7VZFPO5.js +91 -0
- package/dist/migrate-platform-E7VZFPO5.js.map +1 -0
- package/dist/optimize-WUJ5ZN5Y.js +109 -0
- package/dist/optimize-WUJ5ZN5Y.js.map +1 -0
- package/dist/perf-UULZSREY.js +200 -0
- package/dist/perf-UULZSREY.js.map +1 -0
- package/dist/pii-QHU32VML.js +146 -0
- package/dist/pii-QHU32VML.js.map +1 -0
- package/dist/pilot-BR6GVK32.js +29 -0
- package/dist/pilot-BR6GVK32.js.map +1 -0
- package/dist/pr-comment-2FOA3EXG.js +81 -0
- package/dist/pr-comment-2FOA3EXG.js.map +1 -0
- package/dist/preview-XNY422OU.js +46 -0
- package/dist/preview-XNY422OU.js.map +1 -0
- package/dist/profile-SQTBNKYS.js +98 -0
- package/dist/profile-SQTBNKYS.js.map +1 -0
- package/dist/promote-FSGUPIPD.js +417 -0
- package/dist/promote-FSGUPIPD.js.map +1 -0
- package/dist/publish-AYCRMCE2.js +739 -0
- package/dist/publish-AYCRMCE2.js.map +1 -0
- package/dist/purge-Y5IOTXKA.js +56 -0
- package/dist/purge-Y5IOTXKA.js.map +1 -0
- package/dist/query-log-SDDGMJLJ.js +112 -0
- package/dist/query-log-SDDGMJLJ.js.map +1 -0
- package/dist/refactor-TC7S43F2.js +5809 -0
- package/dist/refactor-TC7S43F2.js.map +1 -0
- package/dist/refresh-MDJYOYV5.js +39 -0
- package/dist/refresh-MDJYOYV5.js.map +1 -0
- package/dist/replay-E4664A5K.js +118 -0
- package/dist/replay-E4664A5K.js.map +1 -0
- package/dist/revert-QWQWCJJB.js +111 -0
- package/dist/revert-QWQWCJJB.js.map +1 -0
- package/dist/review-7CAVLD67.js +164 -0
- package/dist/review-7CAVLD67.js.map +1 -0
- package/dist/rollback-suggest-C6D5YFCA.js +79 -0
- package/dist/rollback-suggest-C6D5YFCA.js.map +1 -0
- package/dist/safer-alternative-QR4QEFUV.js +84 -0
- package/dist/safer-alternative-QR4QEFUV.js.map +1 -0
- package/dist/safety-OFWUFLK4.js +165 -0
- package/dist/safety-OFWUFLK4.js.map +1 -0
- package/dist/savings-MEBE4TXI.js +95 -0
- package/dist/savings-MEBE4TXI.js.map +1 -0
- package/dist/scan-secrets-XCUBMLHL.js +54 -0
- package/dist/scan-secrets-XCUBMLHL.js.map +1 -0
- package/dist/schema-7JZIG6QR.js +447 -0
- package/dist/schema-7JZIG6QR.js.map +1 -0
- package/dist/script-BMYVBHFR.js +167 -0
- package/dist/script-BMYVBHFR.js.map +1 -0
- package/dist/search-TA3C3AZT.js +151 -0
- package/dist/search-TA3C3AZT.js.map +1 -0
- package/dist/seed-W4Q3L2IU.js +101 -0
- package/dist/seed-W4Q3L2IU.js.map +1 -0
- package/dist/sketch-6B2V6FJV.js +83 -0
- package/dist/sketch-6B2V6FJV.js.map +1 -0
- package/dist/snapshot-YMVS322L.js +171 -0
- package/dist/snapshot-YMVS322L.js.map +1 -0
- package/dist/snippets-EVTN63OU.js +74 -0
- package/dist/snippets-EVTN63OU.js.map +1 -0
- package/dist/standards-FGJW3CQL.js +238 -0
- package/dist/standards-FGJW3CQL.js.map +1 -0
- package/dist/suggest-V3LVIFZ5.js +44 -0
- package/dist/suggest-V3LVIFZ5.js.map +1 -0
- package/dist/suggest-constraints-EX2FCWOQ.js +154 -0
- package/dist/suggest-constraints-EX2FCWOQ.js.map +1 -0
- package/dist/suite-YTQ3CNX5.js +85 -0
- package/dist/suite-YTQ3CNX5.js.map +1 -0
- package/dist/telemetry-KOIY3NEQ.js +90 -0
- package/dist/telemetry-KOIY3NEQ.js.map +1 -0
- package/dist/template-MUJ6X6LN.js +396 -0
- package/dist/template-MUJ6X6LN.js.map +1 -0
- package/dist/test-XFSQHR2S.js +169 -0
- package/dist/test-XFSQHR2S.js.map +1 -0
- package/dist/trial-GFTGYCR3.js +31 -0
- package/dist/trial-GFTGYCR3.js.map +1 -0
- package/dist/validate-LFDEZFFH.js +107 -0
- package/dist/validate-LFDEZFFH.js.map +1 -0
- package/dist/verify-KRDYOJCR.js +76 -0
- package/dist/verify-KRDYOJCR.js.map +1 -0
- package/dist/watch-FSG23RR3.js +80 -0
- package/dist/watch-FSG23RR3.js.map +1 -0
- package/dist/xcompare-U4TXTTIR.js +87 -0
- package/dist/xcompare-U4TXTTIR.js.map +1 -0
- package/package.json +2 -2
- package/dist/cli.cjs +0 -19298
- package/dist/cli.cjs.map +0 -1
- package/dist/cli.d.cts +0 -1
- package/dist/cli.d.ts +0 -1
package/dist/cli.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/connection.ts","../src/commands/init.ts","../src/util/help-catalog.ts","../src/commands/validate.ts","../src/util/mapping.ts","../src/util/color.ts","../src/commands/compare.ts","../src/commands/build.ts","../src/commands/publish.ts","../src/commands/script.ts","../src/commands/import.ts","../src/commands/extract.ts","../src/commands/completion.ts","../src/commands/drift.ts","../src/commands/format.ts","../src/commands/lint.ts","../src/commands/docs.ts","../src/commands/verify.ts","../src/commands/revert.ts","../src/commands/snapshot.ts","../src/util/ai-explain.ts","../src/commands/graph.ts","../src/commands/lineage.ts","../src/commands/diagnose.ts","../src/commands/review.ts","../src/commands/impact.ts","../src/commands/cost-estimate.ts","../src/commands/pr-comment.ts","../src/commands/template.ts","../src/commands/anonymize.ts","../src/commands/test.ts","../src/commands/branch.ts","../src/commands/schema.ts","../src/commands/suggest.ts","../src/commands/history.ts","../src/commands/audit-log.ts","../src/commands/install-hooks.ts","../src/commands/telemetry.ts","../src/commands/seed.ts","../src/commands/suite.ts","../src/commands/refactor.ts","../src/commands/license.ts","../src/commands/mcp.ts","../src/commands/ai.ts","../src/commands/explain.ts","../src/commands/feedback.ts","../src/commands/features.ts","../src/commands/hosts.ts","../src/commands/safety.ts","../src/commands/pii.ts","../src/commands/bisect.ts","../src/commands/changelog.ts","../src/commands/replay.ts","../src/commands/drift-gate.ts","../src/commands/promote.ts","../src/commands/data-fit.ts","../src/commands/data-compare.ts","../src/commands/approval.ts","../src/commands/advise-tests.ts","../src/commands/safer-alternative.ts","../src/commands/sketch.ts","../src/commands/design.ts","../src/commands/optimize.ts","../src/commands/rollback-suggest.ts","../src/commands/compare-profiles.ts","../src/commands/explorer.ts","../src/commands/catalog.ts","../src/util/logger.ts","../src/commands/xcompare.ts","../src/commands/profile.ts","../src/commands/suggest-constraints.ts","../src/commands/purge.ts","../src/commands/preview.ts","../src/commands/refresh.ts","../src/commands/discover.ts","../src/commands/find.ts","../src/commands/scan-secrets.ts","../src/commands/error-lookup.ts","../src/commands/deploy-status.ts","../src/commands/approval-chain.ts","../src/commands/standards.ts","../src/commands/perf.ts","../src/commands/migrate-platform.ts","../src/commands/migrate-from-dbt.ts","../src/commands/backlog.ts","../src/commands/watch.ts","../src/commands/bookmarks.ts","../src/commands/snippets.ts","../src/commands/generate.ts","../src/commands/exec.ts","../src/commands/search.ts","../src/commands/query-log.ts","../src/commands/savings.ts","../src/commands/trial.ts","../src/commands/pilot.ts","../src/util/errorReporting.ts","../src/cli.ts"],"sourcesContent":["import { Command } from 'commander';\nimport {\n createConnection,\n defaultProfilesPath,\n getProfile,\n loadProfiles,\n removeProfile,\n upsertProfile,\n type DatabricksConnectionProfile,\n type DatabricksAuth,\n} from '@ddt-tools/core';\n\n/**\n * `ddt connection` — manage Databricks workspace connection profiles.\n *\n * Profiles live at `~/.ddt/profiles.json` (overridable via `$DDT_PROFILES_PATH`).\n * add / list / get / remove are wired today. `test` (probe a profile via\n * the workspace REST API) waits on the OAuth U2M flow before it can land.\n */\nexport function connectionCommand(): Command {\n const cmd = new Command('connection').description('Manage Databricks connection profiles.');\n\n cmd\n .command('add <name>')\n .description('Store a new connection profile.')\n .option('--host <host>', 'Workspace host, e.g. dbc-12345-abcd.cloud.databricks.com')\n .option('--auth <method>', 'One of: pat | oauth-m2m | oauth-u2m | azure-ad | google-idc', 'pat')\n .option(\n '--token <token>',\n 'PAT token — use env:DATABRICKS_TOKEN to reference an env var, never inline a secret',\n )\n .option('--client-id <id>', 'OAuth M2M / Azure AD client ID')\n .option('--client-secret <secret>', 'OAuth M2M / Azure AD client secret')\n .option('--tenant-id <id>', 'Azure AD tenant ID')\n .option(\n '--service-account-key-path <path>',\n 'Path to a GCP service-account key JSON file (for google-idc auth)',\n )\n .requiredOption('--warehouse-id <id>', 'SQL warehouse ID for DDL operations')\n .option('--catalog <catalog>', 'Default Unity Catalog catalog')\n .option('--schema <schema>', 'Default schema')\n .action(async (name: string, opts) => {\n if (!opts.host) throw new Error('--host is required');\n const auth = buildAuth(opts);\n const profile: DatabricksConnectionProfile = {\n name,\n platform: 'Databricks',\n auth,\n warehouseId: String(opts.warehouseId),\n ...(opts.catalog ? { catalog: String(opts.catalog) } : {}),\n ...(opts.schema ? { schema: String(opts.schema) } : {}),\n };\n await upsertProfile(profile);\n console.log(`Saved profile \"${name}\" → ${defaultProfilesPath()}`);\n });\n\n cmd\n .command('list')\n .description('List configured Databricks profiles.')\n .action(async () => {\n const profiles = await loadProfiles();\n if (profiles.length === 0) {\n console.log(`(no profiles configured at ${defaultProfilesPath()})`);\n return;\n }\n for (const p of profiles) {\n console.log(`${p.name}\\t${p.auth.method}\\t${p.auth.host}\\twarehouse=${p.warehouseId}`);\n }\n });\n\n cmd\n .command('get <name>')\n .description('Print a profile (secrets are redacted).')\n .action(async (name: string) => {\n const p = await getProfile(name);\n const redacted: DatabricksConnectionProfile = {\n ...p,\n auth: redactAuth(p.auth),\n };\n console.log(JSON.stringify(redacted, null, 2));\n });\n\n cmd\n .command('remove <name>')\n .description('Delete a connection profile.')\n .action(async (name: string) => {\n const removed = await removeProfile(name);\n console.log(removed ? `Removed profile \"${name}\".` : `No profile \"${name}\" found.`);\n if (!removed) process.exitCode = 1;\n });\n\n cmd\n .command('test <name>')\n .description(\n 'Probe a connection profile via the workspace REST API (`/api/2.0/preview/scim/v2/Me`).',\n )\n .action(async (name: string) => {\n const profile = await getProfile(name);\n const conn = createConnection(profile);\n try {\n await conn.connect();\n const info = await conn.test();\n console.log(`OK ${name}`);\n console.log(` host: ${profile.auth.host}`);\n console.log(` account: ${info.account}`);\n console.log(` version: ${info.version}`);\n } catch (err) {\n console.error(`FAIL ${name}: ${err instanceof Error ? err.message : String(err)}`);\n process.exitCode = 1;\n } finally {\n await conn.disconnect();\n }\n });\n\n return cmd;\n}\n\nfunction buildAuth(opts: {\n host?: string;\n auth?: string;\n token?: string;\n clientId?: string;\n clientSecret?: string;\n tenantId?: string;\n serviceAccountKeyPath?: string;\n}): DatabricksAuth {\n const host = String(opts.host);\n const method = String(opts.auth ?? 'pat').toLowerCase();\n switch (method) {\n case 'pat':\n case 'personal_access_token':\n if (!opts.token) throw new Error('--token is required for PAT auth');\n return { method: 'PERSONAL_ACCESS_TOKEN', host, token: String(opts.token) };\n case 'oauth-m2m':\n case 'oauth_m2m':\n if (!opts.clientId || !opts.clientSecret) {\n throw new Error('--client-id and --client-secret are required for OAuth M2M');\n }\n return {\n method: 'OAUTH_M2M',\n host,\n clientId: String(opts.clientId),\n clientSecret: String(opts.clientSecret),\n };\n case 'oauth-u2m':\n case 'oauth_u2m':\n return { method: 'OAUTH_U2M', host };\n case 'azure-ad':\n case 'azure_ad':\n if (!opts.tenantId || !opts.clientId) {\n throw new Error('--tenant-id and --client-id are required for Azure AD');\n }\n return {\n method: 'AZURE_AD',\n host,\n tenantId: String(opts.tenantId),\n clientId: String(opts.clientId),\n ...(opts.clientSecret ? { clientSecret: String(opts.clientSecret) } : {}),\n };\n case 'google-idc':\n case 'google_idc':\n if (!opts.serviceAccountKeyPath) {\n throw new Error('--service-account-key-path is required for google-idc auth');\n }\n return {\n method: 'GOOGLE_IDC',\n host,\n serviceAccountKeyPath: String(opts.serviceAccountKeyPath),\n };\n default:\n throw new Error(`Unknown --auth value: ${method}`);\n }\n}\n\nfunction redactAuth(auth: DatabricksAuth): DatabricksAuth {\n if (auth.method === 'PERSONAL_ACCESS_TOKEN' && auth.token && !auth.token.startsWith('env:')) {\n return { ...auth, token: '<redacted>' };\n }\n if (auth.method === 'OAUTH_M2M' && auth.clientSecret && !auth.clientSecret.startsWith('env:')) {\n return { ...auth, clientSecret: '<redacted>' };\n }\n if (auth.method === 'AZURE_AD' && auth.clientSecret && !auth.clientSecret.startsWith('env:')) {\n return { ...auth, clientSecret: '<redacted>' };\n }\n return auth;\n}\n","import path from 'node:path';\nimport { promises as fs } from 'node:fs';\nimport { Command } from 'commander';\nimport { newProjectTemplate, saveProject, type ProjectScope } from '@ddt-tools/core';\n\nexport function initCommand(): Command {\n const cmd = new Command('init');\n cmd\n .description('Initialize a new DDT project in the current directory.')\n .option('--name <name>', 'Project name', 'NewDatabricksProject')\n .option('--scope <scope>', 'Project scope: metastore | catalog | schema', 'catalog')\n .option('--catalog <catalog>', 'Unity Catalog catalog name (required for catalog/schema scope)')\n .option('--schema <schema>', 'Schema name (required for schema scope)')\n .option('--dir <dir>', 'Target directory (default: cwd)', process.cwd())\n .action(async (opts) => {\n const scopeType = String(opts.scope) as ProjectScope['type'];\n if (!['metastore', 'catalog', 'schema'].includes(scopeType)) {\n throw new Error(`Invalid --scope: ${opts.scope}. Use metastore | catalog | schema.`);\n }\n const scope: ProjectScope = { type: scopeType };\n if (scopeType !== 'metastore') {\n if (!opts.catalog) throw new Error(`--catalog is required for scope=${scopeType}`);\n scope.catalog = String(opts.catalog);\n }\n if (scopeType === 'schema') {\n if (!opts.schema) throw new Error('--schema is required for scope=schema');\n scope.schema = String(opts.schema);\n }\n const root = path.resolve(String(opts.dir));\n await fs.mkdir(root, { recursive: true });\n const project = newProjectTemplate(String(opts.name), scope);\n const projectPath = path.join(root, `${project.name}.ddtproj`);\n await saveProject(projectPath, project);\n const seedFolders = ['catalogs', 'scripts/pre', 'scripts/post'];\n for (const f of seedFolders) await fs.mkdir(path.join(root, f), { recursive: true });\n console.log(`Created ${projectPath}`);\n console.log(\n ` Scope: ${scopeType}${scope.catalog ? ' / ' + scope.catalog : ''}${scope.schema ? ' / ' + scope.schema : ''}`,\n );\n console.log(` Next: ddt extract --connection <profile> --output ${root}`);\n });\n return cmd;\n}\n","/**\n * Per-command --help enrichments — show 3-5 related catalog entries\n * under each command's help screen, with a one-line summary and a\n * pointer to `ddt explain <name>` for the full entry.\n *\n * Free-tier discoverability: a user who opens `ddt publish --help`\n * lands on a clear list of the deployment options that govern the\n * command's safety behaviour, without needing to know they exist or\n * read the project format reference first.\n *\n * Mirrors `Snowflake/packages/cli/src/util/help-catalog.ts`.\n */\nimport type { Command } from 'commander';\nimport { DEPLOY_OPTIONS_CATALOG, type OptionEntry } from '@ddt-tools/core/options';\n\nconst CATALOG_BY_NAME: Map<string, OptionEntry> = new Map(\n DEPLOY_OPTIONS_CATALOG.map((entry) => [entry.name, entry]),\n);\n\n/**\n * Attach an \"After\" help block listing the named catalog entries with\n * one-line summaries. Unknown keys are silently skipped so a stale\n * mapping never breaks --help.\n */\nexport function attachRelatedOptions(cmd: Command, names: readonly string[]): void {\n const entries: OptionEntry[] = [];\n for (const n of names) {\n const e = CATALOG_BY_NAME.get(n);\n if (e) entries.push(e);\n }\n if (entries.length === 0) return;\n const maxName = entries.reduce((m, e) => Math.max(m, e.name.length), 0);\n const lines = [\n '',\n 'Related options (run `ddt explain <name>` for safety tier, default, and example):',\n ...entries.map((e) => ` ${e.name.padEnd(maxName)} ${e.summary}`),\n ];\n cmd.addHelpText('after', lines.join('\\n'));\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport {\n discoverObjectFiles,\n loadProject,\n parseProjectModel,\n validate as validateNs,\n variables as variablesNs,\n} from '@ddt-tools/core';\nimport { attachRelatedOptions } from '../util/help-catalog.js';\n\n/**\n * `ddt validate` — schema-shape sanity check on a `.ddtproj`. With\n * `--references`, runs the build-time semantic resolver: every\n * object reference is classified as resolved / dangling / external /\n * temporary / dynamic, with warnings for unresolved references.\n *\n * Mirrors `sdt validate`. Column-level resolution is Phase 2.\n */\nexport function validateCommand(): Command {\n const cmd = new Command('validate');\n cmd\n .description(\n 'Validate a .ddtproj — schema check; optionally resolve every object reference (--references).',\n )\n .requiredOption('-p, --project <path>', 'Path to .ddtproj')\n .option(\n '--references',\n 'Run the build-time semantic resolver — flag dangling/external/temp/dynamic references.',\n )\n .option(\n '--columns',\n '[--references] Also resolve every column reference. ERROR on missing column on a known table. Phase 2 of the SSDT-build-equivalent resolver.',\n )\n .option(\n '--min-severity <s>',\n '[--references] Filter findings: error | warning | info. Default info.',\n 'info',\n )\n .option('--format <fmt>', '[--references] table | json. Default table.', 'table')\n .option('-o, --out <path>', '[--references] Write report to file instead of stdout.')\n .option(\n '--check-variables',\n 'VARSYNTAX.4 — refuse if any `$(VAR)` reference in a tracked `.sql` file is not declared in built-ins / deploymentProfiles[*].variables. Exits 1 when undeclared references are found.',\n )\n .action(async (opts) => {\n const loaded = await loadProject(String(opts.project));\n const files = await discoverObjectFiles(loaded);\n console.log(`Project ${loaded.project.name} v${loaded.project.version} is valid.`);\n console.log(\n ` Scope: ${loaded.project.scope.type}${loaded.project.scope.catalog ? '/' + loaded.project.scope.catalog : ''}${loaded.project.scope.schema ? '/' + loaded.project.scope.schema : ''}`,\n );\n console.log(` Files: ${files.length}`);\n console.log(` Profiles: ${Object.keys(loaded.project.deploymentProfiles ?? {}).length}`);\n\n if (opts.checkVariables) {\n const projRoot = path.dirname(path.resolve(String(opts.project)));\n const fileContents = await Promise.all(\n files.map(async (f) => {\n const relPath = path.relative(projRoot, f).split(path.sep).join('/');\n const content = await fs.readFile(f, 'utf8');\n return { path: relPath, content };\n }),\n );\n const profilesBlock = loaded.project.deploymentProfiles ?? {};\n const profileVariableKeys = Object.values(profilesBlock).map((p) =>\n Object.keys(p.variables ?? {}),\n );\n const report = variablesNs.checkVariableReferences({\n files: fileContents,\n deploymentProfileVariables: profileVariableKeys,\n });\n if (report.undeclared.length > 0) {\n const msg = variablesNs.formatCheckVariablesReport(report);\n process.stdout.write(msg + '\\n');\n process.exitCode = 1;\n return;\n }\n console.log(` Variables: ${report.references.length} reference(s), all declared.`);\n }\n\n if (!opts.references) return;\n\n console.log('');\n console.log('Resolving references…');\n const model = await parseProjectModel(loaded);\n const report = validateNs.validateProject(model, {\n source: String(opts.project),\n minSeverity: opts.minSeverity as validateNs.BuildSeverity,\n columns: Boolean(opts.columns),\n });\n\n const fmt = String(opts.format ?? 'table').toLowerCase();\n const payload =\n fmt === 'json' ? JSON.stringify(report, null, 2) : validateNs.formatBuildReport(report);\n if (opts.out) {\n const out = path.resolve(String(opts.out));\n await fs.mkdir(path.dirname(out), { recursive: true });\n await fs.writeFile(out, payload + (payload.endsWith('\\n') ? '' : '\\n'), 'utf8');\n console.log(\n `Wrote ${out} (${payload.length} bytes, ${report.findings.length} finding(s)).`,\n );\n } else {\n process.stdout.write(payload + (payload.endsWith('\\n') ? '' : '\\n'));\n }\n\n if (report.totals.error > 0) process.exitCode = 1;\n });\n attachRelatedOptions(cmd, [\n 'compare.ignoreCase',\n 'compare.ignoreComments',\n 'compare.ignoreFormattingDifferences',\n ]);\n return cmd;\n}\n","import { promises as fs } from 'node:fs';\nimport { Option, type Command } from 'commander';\nimport { mappingFromArgs, mappingFromFile, type NameMapping } from '@ddt-tools/core';\n\nexport interface MappingOptions {\n map?: string[];\n mapFile?: string;\n mapCaseSensitive?: boolean;\n mapRewriteStandalone?: boolean;\n mapRewriteStrings?: boolean;\n}\n\n/** Attach `--map`, `--map-file`, `--map-case-sensitive`, `--map-rewrite-standalone`, `--map-rewrite-strings` to a command. */\nexport function addMappingFlags(cmd: Command): Command {\n return cmd\n .option(\n '--map <src=tgt>',\n 'Logical-name mapping (repeatable). Examples: DB_A=DB_B, DB_A.STAGING=DB_B.RAW. Rewrites source-side FQNs and DDL body refs.',\n (value: string, previous: string[]) => [...previous, value],\n [] as string[],\n )\n .option('--map-file <path>', 'JSON file of mappings.')\n .addOption(\n new Option(\n '--map-case-sensitive',\n 'Match identifiers case-sensitively. Default: insensitive.',\n ).default(false),\n )\n .addOption(\n new Option(\n '--map-rewrite-standalone',\n 'Rewrite standalone one-part refs (e.g. USE DATABASE DB_A). Default: off (safer).',\n ).default(false),\n )\n .addOption(\n new Option(\n '--map-rewrite-strings',\n 'Phase 3: also rewrite FQN-shaped tokens inside string literals (best-effort, may produce false positives in legitimate string content). Default: off.',\n ).default(false),\n );\n}\n\n/** Build a `NameMapping` from `--map`/`--map-file` flag values. Returns undefined when no mappings supplied. */\nexport async function buildMappingFromOptions(\n opts: MappingOptions,\n): Promise<NameMapping | undefined> {\n const flagMappings = Array.isArray(opts.map) ? opts.map : [];\n let mapping: NameMapping = { entries: [] };\n if (opts.mapFile) {\n const raw = await fs.readFile(String(opts.mapFile), 'utf8');\n mapping = mappingFromFile(JSON.parse(raw));\n }\n if (flagMappings.length > 0) {\n const fromArgs = mappingFromArgs(flagMappings);\n mapping = { entries: [...mapping.entries, ...fromArgs.entries] };\n }\n if (mapping.entries.length === 0) return undefined;\n if (opts.mapCaseSensitive) mapping.caseSensitive = true;\n if (opts.mapRewriteStandalone) mapping.rewriteStandaloneRefs = true;\n if (opts.mapRewriteStrings) mapping.rewriteInsideStrings = true;\n return mapping;\n}\n\n/** Render a one-line summary of a NameMapping for the operator's log output. */\nexport function describeMapping(mapping: NameMapping | undefined): string {\n if (!mapping || mapping.entries.length === 0) return '';\n return mapping.entries.map((e) => `${e.source}→${e.target}`).join(', ');\n}\n","/**\n * ANSI severity coloring for CLI output, DDT side. Paired with\n * `Snowflake/packages/cli/src/util/color.ts` byte-for-byte at the\n * API level.\n */\nexport type ColorMode = 'always' | 'never' | 'auto';\n\nconst ANSI = {\n reset: '\\x1b[0m',\n bold: '\\x1b[1m',\n red: '\\x1b[31m',\n yellow: '\\x1b[33m',\n cyan: '\\x1b[36m',\n green: '\\x1b[32m',\n gray: '\\x1b[90m',\n};\n\nexport function resolveColorMode(flag: string | undefined): boolean {\n const mode = (flag ?? 'auto').toLowerCase() as ColorMode;\n if (mode === 'always') return true;\n if (mode === 'never') return false;\n if (process.env.NO_COLOR) return false;\n return Boolean(process.stdout.isTTY);\n}\n\nexport interface Colorizer {\n unrecoverable(s: string): string;\n destructive(s: string): string;\n expensive(s: string): string;\n warning(s: string): string;\n safe(s: string): string;\n dim(s: string): string;\n applyToBlock(block: string): string;\n}\n\nexport function makeColorizer(enabled: boolean): Colorizer {\n if (!enabled) {\n const identity = (s: string): string => s;\n return {\n unrecoverable: identity,\n destructive: identity,\n expensive: identity,\n warning: identity,\n safe: identity,\n dim: identity,\n applyToBlock: identity,\n };\n }\n const wrap =\n (codes: string) =>\n (s: string): string =>\n `${codes}${s}${ANSI.reset}`;\n return {\n unrecoverable: wrap(ANSI.bold + ANSI.red),\n destructive: wrap(ANSI.red),\n expensive: wrap(ANSI.yellow),\n warning: wrap(ANSI.cyan),\n safe: wrap(ANSI.green),\n dim: wrap(ANSI.gray),\n applyToBlock(block: string): string {\n return block\n .split('\\n')\n .map((line) => {\n if (/UNRECOVERABLE/.test(line) || line.includes('🛑'))\n return ANSI.bold + ANSI.red + line + ANSI.reset;\n if (/DESTRUCTIVE/.test(line)) return ANSI.red + line + ANSI.reset;\n if (/EXPENSIVE/.test(line)) return ANSI.yellow + line + ANSI.reset;\n if (/WARNING/.test(line) || line.includes('⚠')) return ANSI.cyan + line + ANSI.reset;\n if (/\\bSAFE\\b|\\bOK\\b/.test(line) || line.includes('✓'))\n return ANSI.green + line + ANSI.reset;\n return line;\n })\n .join('\\n');\n },\n };\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport {\n CompareEngine,\n PacSource,\n ai,\n compileSlice,\n pac as pacNs,\n renderHtmlReport,\n safety,\n typecheck,\n writeCompareHistory,\n} from '@ddt-tools/core';\nimport { addMappingFlags, buildMappingFromOptions, describeMapping } from '../util/mapping.js';\nimport { attachRelatedOptions } from '../util/help-catalog.js';\nimport { makeColorizer, resolveColorMode } from '../util/color.js';\n\n/**\n * `ddt compare` — pac↔pac compare today. Project↔pac and project↔live require\n * the SQL parser pass (v0.3 polish) + a live driver session.\n *\n * Supports logical-name mapping (`--map`, `--map-file`) so two pacs whose\n * database / schema names differ can compare semantically. See\n * `docs/LOGICAL_NAME_MAPPING.md`.\n */\nexport function compareCommand(): Command {\n const cmd = new Command('compare');\n cmd\n .description('Compare two .ddtpac files (pac↔pac); project / live compare pending v0.3 polish.')\n .requiredOption('--source <path>', 'Source .ddtpac (the desired state).')\n .requiredOption('--target <path>', 'Target .ddtpac (the current state).')\n .option('--ignore-case', 'Compare object FQNs case-insensitively.', false)\n .option(\n '--json',\n 'Emit a JSON CompareResult instead of human-readable output. (Alias for --format json.)',\n false,\n )\n .option(\n '--format <fmt>',\n 'Output format: summary | json | markdown. Default summary.',\n 'summary',\n )\n .option('--report-html <path>', 'Also write a self-contained HTML compare-report to <path>.')\n .option(\n '--no-slice',\n \"Disable the source pac's Project Slice (if it has one). Default: a sliced pac is partitioned automatically.\",\n )\n .option(\n '--explain',\n 'After the diff, call the configured AI provider to narrate each change in plain English with reasoning. Requires `ddt ai` to be configured.',\n false,\n )\n .option(\n '--color <mode>',\n 'Colorize severity output: always | never | auto. Default auto (color on TTY).',\n 'auto',\n )\n .option(\n '--type-safe',\n 'After the compare, run the TYPECHECK.1 impact analyzer. Exits with code 2 if the configured --break-on threshold is reached (default `error`). CI-friendly gate — pair with `--format json` for machine-readable output.',\n false,\n )\n .option(\n '--break-on <severity>',\n 'TYPECHECK.2 threshold for --type-safe: `error` (exit 2 on any error ripple, default) | `warning` (exit 2 on any error OR warning ripple, strict CI mode).',\n 'error',\n )\n .option(\n '--write-impact [path]',\n 'Write the TYPECHECK.1 impact analysis to a JSON file the VS Code extension can surface as squiggle-underlines. Default path: `.ddt/impact.json` resolved relative to CWD. Composes with `--type-safe` — the file is written before the gate decides exit code.',\n )\n .option(\n '--no-history',\n 'Skip writing the compare-history audit record (AUDITCMP.1). Default: every compare run writes a record to `.ddt/history/compare/`, exportable via `ddt audit-log emit`.',\n );\n addMappingFlags(cmd);\n cmd.action(async (opts) => {\n const nameMapping = await buildMappingFromOptions(opts);\n const engine = new CompareEngine();\n const source = new PacSource(String(opts.source), 'source');\n const target = new PacSource(String(opts.target), 'target');\n\n // Auto-pull slice from the source pac's manifest unless --no-slice was set.\n let slice: ReturnType<typeof compileSlice> | undefined;\n if (opts.slice !== false) {\n const srcPac = await pacNs.readPac(String(opts.source));\n if (srcPac.manifest.slice) slice = compileSlice(srcPac.manifest.slice);\n }\n\n const startedAt = new Date().toISOString();\n const result = await engine.compare(source, target, {\n ignoreCase: !!opts.ignoreCase,\n ...(nameMapping ? { nameMapping } : {}),\n ...(slice ? { sliceFilter: slice } : {}),\n });\n\n // AUDITCMP.1 — compare operations leave the same audit trail deploys\n // do. Written before the format-specific early returns so every\n // output mode is covered. Best-effort: a failed write never breaks\n // the compare itself.\n if (opts.history !== false) {\n const finishedAt = new Date().toISOString();\n try {\n const histAssessment = safety.assess(result);\n const changed = result.summary.added + result.summary.removed + result.summary.modified;\n await writeCompareHistory(path.dirname(path.resolve(String(opts.source))), {\n startedAt,\n finishedAt,\n durationMs: Date.parse(finishedAt) - Date.parse(startedAt),\n outcome: histAssessment.blocked\n ? 'BLOCKED'\n : changed === 0\n ? 'NO_CHANGES'\n : 'CHANGES_FOUND',\n source: { kind: result.source.kind, label: result.source.label },\n target: { kind: result.target.kind, label: result.target.label },\n summary: result.summary,\n sliceApplied: Boolean(slice),\n ...(histAssessment.blocked && histAssessment.blockReason\n ? { blockReason: histAssessment.blockReason }\n : {}),\n });\n } catch {\n /* audit trail is best-effort; never fail the compare over it */\n }\n }\n\n if (opts.reportHtml) {\n const html = renderHtmlReport(result, {\n title: `Compare ${result.source.label} → ${result.target.label}`,\n safety: safety.assess(result),\n });\n const htmlPath = path.resolve(String(opts.reportHtml));\n await fs.mkdir(path.dirname(htmlPath), { recursive: true });\n await fs.writeFile(htmlPath, html, 'utf8');\n console.error(`Wrote ${htmlPath} (${html.length} bytes).`);\n }\n\n const fmt = opts.json ? 'json' : String(opts.format ?? 'summary').toLowerCase();\n if (fmt === 'json') {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n if (fmt === 'markdown') {\n const assessment = safety.assess(result);\n console.log(renderCompareMarkdown(result, assessment));\n return;\n }\n const s = result.summary;\n console.log(`Source: ${result.source.kind}:${result.source.label}`);\n console.log(`Target: ${result.target.kind}:${result.target.label}`);\n const mappingSummary = describeMapping(nameMapping);\n if (mappingSummary) console.log(`Mapping: ${mappingSummary}`);\n if (slice) {\n const outside = result.outsideScope?.length ?? 0;\n const refs = result.referenced?.length ?? 0;\n console.log(\n `Slice active: ${result.objects.length} owned · ${outside} outside scope (untouched) · ${refs} referenced`,\n );\n }\n console.log(`Summary: +${s.added} -${s.removed} ~${s.modified} =${s.unchanged}`);\n for (const o of result.objects) {\n if (o.kind === 'unchanged') continue;\n const glyph = o.kind === 'added' ? '+' : o.kind === 'removed' ? '-' : '~';\n console.log(` ${glyph} ${o.identity.objectType} ${o.identity.fqn}`);\n if (o.kind === 'modified' && o.changes) {\n for (const c of o.changes) {\n console.log(\n ` • ${c.path}: ${JSON.stringify(c.target)} → ${JSON.stringify(c.source)}`,\n );\n }\n }\n }\n\n // Reversibility-grouped safety findings — Unrecoverable first (highest\n // urgency), then Data-impacting, then Reversible. Empty buckets are\n // skipped, and an empty assessment is silent.\n const assessment = safety.assess(result);\n const buckets = safety.groupByReversibility(assessment);\n const total =\n buckets.unrecoverable.length + buckets.dataImpacting.length + buckets.reversible.length;\n if (total > 0) {\n const colorize = makeColorizer(resolveColorMode(opts.color));\n console.log('');\n console.log('Safety findings (grouped by reversibility):');\n const block = safety.formatReversibilityBuckets(buckets);\n const colored = colorize.applyToBlock(block);\n for (const line of colored.split('\\n')) console.log(' ' + line);\n if (assessment.blocked && assessment.blockReason) {\n console.error(' ' + colorize.unrecoverable('BLOCKED: ' + assessment.blockReason));\n }\n }\n\n // AI-narrated diff (--explain). Calls the configured provider with a\n // structured prompt containing the diff summary + per-object changes\n // + safety findings.\n if (opts.explain) {\n console.log('');\n console.log('AI explanation:');\n try {\n const userPrompt = buildExplainPrompt(result, assessment);\n const reply = await ai.complete(\n [\n { role: 'system', content: SYSTEM_PROMPT },\n { role: 'user', content: userPrompt },\n ],\n { feature: 'compare.explain' },\n );\n for (const line of reply.text.split('\\n')) console.log(' ' + line);\n } catch (err) {\n console.error(' --explain failed: ' + (err instanceof Error ? err.message : String(err)));\n console.error(\n ' Run `ddt ai status` to verify your AI provider is configured (`ddt ai test` to send a probe).',\n );\n }\n }\n\n // --write-impact: TYPECHECK.4 — write the impact analysis to a\n // JSON file the VS Code provider reads. Always runs the analyzer\n // (even when --type-safe is off) so the editor surface is\n // independent of the CI-gate flag. Composes with --type-safe.\n if (opts.writeImpact !== undefined) {\n await writeImpactJson(\n result,\n opts.writeImpact === true ? undefined : String(opts.writeImpact),\n );\n }\n\n // --type-safe: TYPECHECK.2 CI gate. Runs the TYPECHECK.1 impact\n // analyzer and exits with code 2 if any error-severity ripple\n // (column-drop or table-drop reaching a dependent object) is\n // detected. Stays silent on a clean diff so this composes well\n // with --format json (which already returned above).\n if (opts.typeSafe) {\n const breakOnRaw = String(opts.breakOn ?? 'error').toLowerCase();\n if (breakOnRaw !== 'error' && breakOnRaw !== 'warning') {\n throw new Error(\n `--break-on must be 'error' or 'warning' (got '${opts.breakOn}'). 'error' fails on any error-severity ripple (default); 'warning' fails on any warning or error ripple (strict CI).`,\n );\n }\n const breakOn = breakOnRaw as 'error' | 'warning';\n const impactFindings = typecheck.analyzeImpact(result);\n const impactSummary = typecheck.summarizeImpact(impactFindings);\n if (impactSummary.findingsCount > 0) {\n console.log('');\n console.log(\n `Type-safety gate (--break-on ${breakOn}) — ${impactSummary.findingsCount} breaking change(s); ${impactSummary.errors} error ripple(s), ${impactSummary.warnings} warning ripple(s); ${impactSummary.affectedObjects.length} dependent object(s).`,\n );\n for (const f of impactFindings) {\n for (const r of f.ripples) {\n const tag = r.severity === 'error' ? 'ERROR' : 'WARN ';\n console.log(\n ` ${tag} ${r.fqn} ← ${f.breakingChangeOn.fqn} (${f.breakingChangeOn.kind})`,\n );\n }\n }\n const failOnError = impactSummary.errors > 0;\n const failOnWarning = breakOn === 'warning' && impactSummary.warnings > 0;\n if (failOnError) {\n console.error(\n `Type-safety gate FAILED — ${impactSummary.errors} error ripple(s). Fix the dependents (drop / update / re-bind) before re-running compare, OR rerun with the change scoped out of the diff.`,\n );\n process.exitCode = 2;\n } else if (failOnWarning) {\n console.error(\n `Type-safety gate FAILED (strict --break-on warning) — ${impactSummary.warnings} warning ripple(s). Tighten the dependent SQL to accept the new type, or drop --break-on warning to allow.`,\n );\n process.exitCode = 2;\n }\n } else {\n console.log('Type-safety gate PASSED — no breaking-change ripples detected.');\n }\n }\n });\n attachRelatedOptions(cmd, [\n 'compare.ignoreCase',\n 'compare.ignoreComments',\n 'compare.ignoreFormattingDifferences',\n 'compare.ignoreClusterBy',\n 'compare.ignorePartitioning',\n 'compare.ignoreStorageLocation',\n ]);\n return cmd;\n}\n\n/**\n * TYPECHECK.4 — write the impact analysis JSON to disk so the VS Code\n * provider can surface it as squiggle-underlines. Defaults to\n * `<cwd>/.ddt/impact.json` (DDT compare today is pac↔pac so we don't\n * resolve a project root from the source arg — that wires in when the\n * project-source variant of compare ships).\n */\nasync function writeImpactJson(\n result: Parameters<typeof typecheck.analyzeImpact>[0],\n explicitPath: string | undefined,\n): Promise<void> {\n const findings = typecheck.analyzeImpact(result);\n const summary = typecheck.summarizeImpact(findings);\n const file: typecheck.ImpactFile = {\n version: typecheck.IMPACT_FILE_VERSION,\n generatedAt: new Date().toISOString(),\n source: `${result.source.kind}:${result.source.label}`,\n target: `${result.target.kind}:${result.target.label}`,\n findings,\n summary,\n };\n const outPath = explicitPath ? path.resolve(explicitPath) : path.resolve('.ddt', 'impact.json');\n await fs.mkdir(path.dirname(outPath), { recursive: true });\n await fs.writeFile(outPath, typecheck.serializeImpactFile(file));\n console.log(\n `Wrote ${outPath} — ${summary.findingsCount} finding(s), ${summary.errors} error / ${summary.warnings} warning ripple(s).`,\n );\n}\n\nexport const SYSTEM_PROMPT = `You are a senior Databricks Unity Catalog DBA reviewing a schema diff. Your job is to narrate the changes in plain English to a teammate who hasn't seen the underlying SQL. For each change, briefly say:\n - what it is (e.g. \"a new fact table is added\")\n - why a reasonable engineer might do this (the intent)\n - what to watch out for (the risk, if any)\n\nBe concrete; use the FQNs you're given. Keep it to 3-6 sentences per object. Don't repeat the raw diff back — explain it.`;\n\nexport function buildExplainPrompt(\n result: {\n source: { label: string };\n target: { label: string };\n objects: Array<{\n kind: string;\n identity: { fqn: string; objectType: string };\n changes?: unknown[];\n }>;\n summary: { added: number; removed: number; modified: number; unchanged: number };\n },\n assessment: {\n unrecoverable: unknown[];\n destructive: unknown[];\n expensive: unknown[];\n warnings: unknown[];\n },\n): string {\n const lines: string[] = [];\n lines.push(`Source: ${result.source.label}`);\n lines.push(`Target: ${result.target.label}`);\n lines.push(\n `Summary: +${result.summary.added} added, -${result.summary.removed} removed, ~${result.summary.modified} modified.`,\n );\n lines.push(\n `Safety: ${assessment.unrecoverable.length} unrecoverable, ${assessment.destructive.length} destructive, ${assessment.expensive.length} expensive, ${assessment.warnings.length} warnings.`,\n );\n lines.push('');\n lines.push('Changes (up to 40):');\n const changed = result.objects.filter((o) => o.kind !== 'unchanged').slice(0, 40);\n for (const o of changed) {\n lines.push(`- ${o.kind} ${o.identity.objectType} ${o.identity.fqn}`);\n }\n if (result.objects.filter((o) => o.kind !== 'unchanged').length > 40) {\n lines.push(\n ` (… ${result.objects.filter((o) => o.kind !== 'unchanged').length - 40} more truncated)`,\n );\n }\n lines.push('');\n lines.push(\n 'Please narrate this diff in plain English. Group related changes together when it helps.',\n );\n return lines.join('\\n');\n}\n\nfunction renderCompareMarkdown(\n result: {\n source: { kind: string; label: string };\n target: { kind: string; label: string };\n objects: Array<{ kind: string; identity: { fqn: string; objectType: string } }>;\n summary: { added: number; removed: number; modified: number; unchanged: number };\n },\n assessment: {\n unrecoverable: unknown[];\n destructive: unknown[];\n expensive: unknown[];\n warnings: unknown[];\n blocked?: boolean;\n blockReason?: string;\n },\n): string {\n const lines: string[] = [];\n lines.push(\n `# Compare: ${result.source.kind}:${result.source.label} → ${result.target.kind}:${result.target.label}`,\n );\n lines.push('');\n lines.push(\n `**Summary**: +${result.summary.added} added · -${result.summary.removed} removed · ~${result.summary.modified} modified · =${result.summary.unchanged} unchanged.`,\n );\n lines.push('');\n lines.push('**Safety**:');\n lines.push(`- 🛑 Unrecoverable: ${assessment.unrecoverable.length}`);\n lines.push(`- 🔥 Destructive: ${assessment.destructive.length}`);\n lines.push(`- ⏱ Expensive: ${assessment.expensive.length}`);\n lines.push(`- ⚠ Warnings: ${assessment.warnings.length}`);\n if (assessment.blocked) {\n lines.push('');\n lines.push(\n `> **BLOCKED**: ${assessment.blockReason ?? 'safety classifier refuses to proceed'}`,\n );\n }\n lines.push('');\n const changed = result.objects.filter((o) => o.kind !== 'unchanged');\n if (changed.length === 0) {\n lines.push('_No object-level changes._');\n return lines.join('\\n');\n }\n lines.push('| Kind | Type | FQN |');\n lines.push('| --- | --- | --- |');\n for (const o of changed) {\n lines.push(`| ${o.kind} | \\`${o.identity.objectType}\\` | \\`${o.identity.fqn}\\` |`);\n }\n return lines.join('\\n');\n}\n","import { Command } from 'commander';\nimport { pac } from '@ddt-tools/core';\n\nexport function buildCommand(): Command {\n const cmd = new Command('build');\n cmd\n .description('Build a .ddtpac from a .ddtproj project.')\n .requiredOption('-p, --project <path>', 'Path to the .ddtproj file')\n .option('-o, --out <path>', 'Output .ddtpac path (default: <projectRoot>/bin/<name>.ddtpac)')\n .action(async (opts) => {\n const result = await pac.buildProject(String(opts.project), {\n outputPath: opts.out ? String(opts.out) : undefined,\n });\n console.log(`Built ${result.outputPath}`);\n console.log(` ${result.fileCount} source file(s), ${result.objectCount} object(s) in model`);\n });\n return cmd;\n}\n","import { Command } from 'commander';\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport {\n CompareEngine,\n DatabricksExecutor,\n PacSource,\n ProjectSource,\n ScriptGenerator,\n ai,\n aiPreflight,\n approval,\n buildDeployManifest,\n buildExecutionPlan,\n colorizeMigrationScript,\n compileSlice,\n createConnection,\n defaultSafePlan,\n executePlan,\n getProfile,\n lintSql,\n loadProject,\n mergeDeployOptions,\n pac as pacNs,\n pacFreshness,\n protectedObjects,\n queryExecution,\n recordDeployChangelog,\n renderHtmlReport,\n resolveProfile,\n safety,\n testFramework,\n validatePlan,\n type CompareSource,\n type StepResult,\n} from '@ddt-tools/core';\nimport { addMappingFlags, buildMappingFromOptions, describeMapping } from '../util/mapping.js';\nimport { attachRelatedOptions } from '../util/help-catalog.js';\n\n/**\n * `ddt publish` — produce a migration script that drives a target toward a\n * source's desired state. `--dry-run` (default) generates the script and\n * prints the safety assessment + default-safe plan summary.\n * `--apply` executes the plan against the named connection profile via\n * `DatabricksExecutor` + `executePlan`, with automatic rollback on\n * partial failure.\n */\nexport function publishCommand(): Command {\n const cmd = new Command('publish');\n cmd\n .description('Generate (and optionally apply) a migration script from source → target.')\n .option(\n '--source <path>',\n 'Source: .ddtproj or .ddtpac (the desired state). Required for a normal publish; omit only with --restore-from-snapshot.',\n )\n .option(\n '--target <path>',\n 'Target: .ddtproj or .ddtpac (the current state). Required for a normal publish; omit only with --restore-from-snapshot.',\n )\n .option(\n '--restore-from-snapshot <batchId>',\n 'Recovery mode: skip the compare step and emit DROP/CREATE … SHALLOW CLONE against the snapshot batch <batchId> from the registry. ' +\n 'Dry-run by default; pass --apply --yes to execute. ' +\n \"This is the command printed by TRUST.4's post-deploy-smoke + TRUST.8's restore-hint when a deploy fails — they tell the operator to run `ddt publish --restore-from-snapshot <id>`.\",\n )\n .option(\n '--snapshot-dir <path>',\n 'Snapshot registry directory used with --restore-from-snapshot.',\n '.ddt/snapshots',\n )\n .option(\n '--out <path>',\n 'Write the generated SQL to this path (currently honored on the --restore-from-snapshot recovery path).',\n )\n .option('--dry-run', 'Print the migration script and safety assessment without applying.', true)\n .option(\n '--apply',\n 'Apply the migration against --connection. Requires --connection. Default false.',\n false,\n )\n .option('--connection <name>', 'Connection profile to apply against. Required with --apply.')\n .option(\n '--yes',\n 'Skip interactive confirmation when applying. Required with --apply (no TTY today).',\n false,\n )\n .option('--variables <kv>', 'Comma-separated KEY=VALUE pairs for $(VAR) substitution.')\n .option('--ignore-case', 'Compare object FQNs case-insensitively.', false)\n .option(\n '--no-rollback',\n 'Skip rollback on partial failure (leaves DIRTY state). Default rollback ON.',\n )\n .option(\n '--require-reversible',\n 'Refuse before any DDL runs if any step lacks reverse SQL.',\n false,\n )\n .option(\n '--manifest <path>',\n 'Write a JSON deploy manifest (every step + status + duration + reverse SQL) to <path>. Audit-friendly.',\n )\n .option('--report-html <path>', 'Write a self-contained HTML compare-report to <path>.')\n .option(\n '--no-lint',\n 'Skip the lint gate. Default: lint the generated script and refuse --apply on ERROR-severity findings.',\n )\n .option(\n '--webhook <url>',\n 'POST a deploy-summary JSON to this URL after --apply completes. Or set $DDT_NOTIFY_WEBHOOK.',\n )\n .option(\n '--profile <name>',\n 'Use the deploymentProfiles[<name>] overlay from --source (.ddtproj). ' +\n 'Pulls profile.connection, profile.variables, profile.deployOptions on top of project defaults.',\n )\n .option(\n '--changelog [catalog]',\n 'After --apply, append a row to <catalog>.__ddt.deploy_log on the workspace. ' +\n \"Defaults catalog to the connection profile's default catalog. Liquibase-style audit table.\",\n )\n .option(\n '--no-slice',\n \"Disable the source's Project Slice (if it has one). Default: a sliced source partitions the diff automatically and target objects outside the slice are left untouched.\",\n )\n .option(\n '--query-tag <tag>',\n 'Tag attached to every executed statement so system.query.history can attribute the deploy. ' +\n 'Prepended as `-- DDT-TAG: <tag>` comment. ' +\n \"Defaults to 'ddt:<projectName>@<projectVersion>:<unix-ms>' when omitted.\",\n )\n .option(\n '--color <mode>',\n 'Color stdout: auto | always | never. Honors NO_COLOR / DDT_NO_COLOR env vars in auto mode.',\n 'auto',\n )\n .option(\n '--ai-preflight',\n \"Before --apply, ask AI to grade the operator's plain-language deploy description against the actual diff + safety findings. Blocks on 'mismatch' unless --confirm-after-preflight-mismatch is also passed.\",\n false,\n )\n .option(\n '--ai-preflight-text <narrative>',\n 'Non-interactive form of --ai-preflight. Supplies the narrative directly instead of reading from stdin.',\n )\n .option(\n '--strict-ai-preflight',\n \"Also block on 'partial' (not just 'mismatch'). Useful for production deploys.\",\n false,\n )\n .option(\n '--confirm-after-preflight-mismatch',\n 'Proceed even when --ai-preflight returns a mismatch verdict. Acknowledges that the AI grader flagged a discrepancy.',\n false,\n )\n .option(\n '--require-approvals <n>',\n 'Multi-approver gate: refuse --apply until <n> distinct approvers have signed off via `ddt approval add <deploy-id> --as <user>`. Team-tier.',\n )\n .option(\n '--approver <ids>',\n 'Comma-separated allow-list of approver IDs honoured by --require-approvals. Empty = any approver counts.',\n )\n .option(\n '--deploy-id <id>',\n 'Stable deploy identifier paired with --require-approvals (default: <connection>:<catalog>.<schema>).',\n )\n .option(\n '--approvals-root <path>',\n 'Approvals directory (default: .ddt/approvals).',\n path.join('.ddt', 'approvals'),\n )\n .option(\n '--allow-protected <fqns>',\n 'Comma-separated FQNs to exempt from the .ddt-protection.json gate. Repeatable.',\n (val: string, prev: string[]) => [...prev, val],\n [] as string[],\n )\n .option(\n '--allow-all-protected',\n 'Bypass all protection gates defined in .ddt-protection.json. Use with care.',\n false,\n )\n .option(\n '--freshness <mode>',\n 'Pac age check: warn (log if stale, continue), strict (block if stale), skip (no check). Default warn.',\n 'warn',\n )\n .option(\n '--post-deploy-tests <project>',\n 'After a successful --apply, discover YAML tests under <project>/tests/ and run them against the same connection. Exits 2 on any blocking (error-severity) DQ failure. Emits POST_DEPLOY_DQ_FAILED hint with --manifest recipe when tests fail.',\n );\n addMappingFlags(cmd);\n cmd.action(async (opts) => {\n // Recovery mode — branch out of the normal compare/apply flow and emit\n // DROP/CREATE … SHALLOW CLONE from a recorded snapshot batch.\n if (opts.restoreFromSnapshot) {\n await runRestoreFromSnapshot(opts);\n return;\n }\n if (!opts.source || !opts.target) {\n throw new Error(\n '--source <path> and --target <path> are required (unless --restore-from-snapshot is given).',\n );\n }\n const nameMapping = await buildMappingFromOptions(opts);\n const sourcePath = String(opts.source);\n const targetPath = String(opts.target);\n const engine = new CompareEngine();\n const src: CompareSource = sourcePath.endsWith('.ddtpac')\n ? new PacSource(sourcePath, 'source')\n : new ProjectSource(sourcePath, 'source');\n const tgt: CompareSource = targetPath.endsWith('.ddtpac')\n ? new PacSource(targetPath, 'target')\n : new ProjectSource(targetPath, 'target');\n\n // Freshness gate — only fires when source is a .ddtpac, before any network call.\n let loadedSrcPac: Awaited<ReturnType<typeof pacNs.readPac>> | undefined;\n if (sourcePath.endsWith('.ddtpac')) {\n loadedSrcPac = await pacNs.readPac(sourcePath);\n const freshnessMode = (opts.freshness as pacFreshness.FreshnessMode | undefined) ?? 'warn';\n if (freshnessMode !== 'skip') {\n const fr = pacFreshness.checkPacFreshness(loadedSrcPac.manifest.builtAt);\n if (fr.status !== 'fresh') {\n const msg = pacFreshness.formatFreshnessWarning(fr, sourcePath);\n if (freshnessMode === 'strict') {\n console.error(msg);\n process.exitCode = 1;\n return;\n } else {\n console.warn(msg);\n }\n }\n }\n }\n\n // Auto-load slice from the source. .ddtpac carries it in manifest;\n // .ddtproj has it as a top-level field. --no-slice bypasses.\n let slice: ReturnType<typeof compileSlice> | undefined;\n if (opts.slice !== false) {\n if (sourcePath.endsWith('.ddtpac')) {\n const srcPac = loadedSrcPac ?? (await pacNs.readPac(sourcePath));\n if (srcPac.manifest.slice) slice = compileSlice(srcPac.manifest.slice);\n } else {\n const loaded = await loadProject(sourcePath);\n if (loaded.project.slice) slice = compileSlice(loaded.project.slice);\n }\n }\n\n const result = await engine.compare(src, tgt, {\n ignoreCase: !!opts.ignoreCase,\n ...(nameMapping ? { nameMapping } : {}),\n ...(slice ? { sliceFilter: slice } : {}),\n });\n const mappingSummary = describeMapping(nameMapping);\n if (mappingSummary) console.log(`Mapping: ${mappingSummary}`);\n if (slice) {\n const outside = result.outsideScope?.length ?? 0;\n const refs = result.referenced?.length ?? 0;\n console.log(\n `Slice active: ${result.objects.length} owned · ${outside} outside scope (untouched) · ${refs} referenced`,\n );\n }\n\n if (opts.reportHtml) {\n const html = renderHtmlReport(result, {\n title: `Publish ${result.source.label} → ${result.target.label}`,\n safety: safety.assess(result),\n });\n const htmlPath = path.resolve(String(opts.reportHtml));\n await fs.mkdir(path.dirname(htmlPath), { recursive: true });\n await fs.writeFile(htmlPath, html, 'utf8');\n console.log(`Wrote HTML report → ${htmlPath}`);\n }\n\n // --profile overlay (project-level deployOptions + variables + connection).\n // VARSYNTAX.2 — also reads from `.ddtpac` manifest's deploymentProfiles\n // snapshot when --source is a built pac (writable since the pac builder\n // snapshots loaded.project.deploymentProfiles into the manifest).\n let profileDeployment: ReturnType<typeof mergeDeployOptions>['deployment'] | undefined;\n let profileVariables: Record<string, string> = {};\n let profileConnection: string | undefined;\n if (opts.profile) {\n const profileName = String(opts.profile);\n if (sourcePath.endsWith('.ddtpac')) {\n const srcPac = loadedSrcPac ?? (await pacNs.readPac(sourcePath));\n const block = srcPac.manifest.deploymentProfiles?.[profileName];\n if (!block) {\n const available = Object.keys(srcPac.manifest.deploymentProfiles ?? {});\n throw new Error(\n `--profile ${profileName}: no deploymentProfile by that name in the pac manifest. ` +\n (available.length === 0\n ? 'The pac carries no deploymentProfiles (was it built before VARSYNTAX.2, or does the .ddtproj declare any?).'\n : `Available: ${available.join(', ')}.`),\n );\n }\n if (block.variables) profileVariables = { ...block.variables };\n if (block.connection) profileConnection = block.connection;\n // pac-snapshot path does NOT overlay profile-level deployOptions —\n // those are already merged into manifest.deployOptions at build\n // time. Leave profileDeployment undefined; the caller falls back\n // to `mergeDeployOptions().deployment`.\n console.log(\n `Profile: ${profileName}${profileConnection ? ` (connection=${profileConnection})` : ''}`,\n );\n } else {\n const loaded = await loadProject(sourcePath);\n const resolved = resolveProfile(loaded, profileName);\n profileDeployment = resolved.deployment;\n profileVariables = resolved.variables;\n profileConnection = resolved.connection;\n console.log(`Profile: ${resolved.name} (connection=${resolved.connection})`);\n }\n }\n\n const assessment = safety.assess(result);\n const deployment = profileDeployment ?? mergeDeployOptions().deployment;\n const variables = { ...profileVariables, ...(parseVariables(opts.variables) ?? {}) };\n\n // VARSYNTAX.3 — assemble the deploy context so `$(DDT_PROFILE)`,\n // `$(DDT_PROJECT_NAME)`, `$(DDT_PROJECT_VERSION)`, `$(DDT_PLATFORM)`,\n // `$(DDT_TIMESTAMP)`, `$(DDT_USER)` substitute without the operator\n // having to pass them via --variables. projectName / projectVersion\n // come from whichever source was loaded (.ddtpac manifest or\n // .ddtproj); profile defaults to undefined unless --profile was used.\n let ctxProjectName: string | undefined;\n let ctxProjectVersion: string | undefined;\n if (sourcePath.endsWith('.ddtpac')) {\n const srcPac = loadedSrcPac ?? (await pacNs.readPac(sourcePath));\n ctxProjectName = srcPac.manifest.projectName;\n ctxProjectVersion = srcPac.manifest.projectVersion;\n } else {\n try {\n const loaded = await loadProject(sourcePath);\n ctxProjectName = loaded.project.name;\n ctxProjectVersion = loaded.project.version;\n } catch {\n // best-effort; built-in vars stay defaulted\n }\n }\n const generateContext: {\n profile?: string;\n projectName?: string;\n projectVersion?: string;\n user?: string;\n } = {\n ...(opts.profile ? { profile: String(opts.profile) } : {}),\n ...(ctxProjectName ? { projectName: ctxProjectName } : {}),\n ...(ctxProjectVersion ? { projectVersion: ctxProjectVersion } : {}),\n };\n\n const generator = new ScriptGenerator();\n const script = generator.generate(result, {\n variables,\n deployment,\n context: generateContext,\n });\n\n const plan = defaultSafePlan(result);\n const validated = validatePlan(result, plan);\n const steps = buildExecutionPlan(result, validated, { deployment });\n\n // Protection gate — block operations on objects declared in .ddt-protection.json.\n const protConfig = await protectedObjects.loadProtectionConfig(path.dirname(sourcePath));\n if (protConfig) {\n const ops = result.objects\n .filter((o) => o.kind !== 'unchanged' && o.kind !== 'added')\n .map((o) => ({\n fqn: o.identity.fqn,\n objectType: String(o.identity.objectType),\n kind: o.kind,\n }));\n const allowedFqns = ((opts.allowProtected as string[]) ?? []).flatMap((s: string) =>\n s.split(',').map((f: string) => f.trim()),\n );\n const violations = protectedObjects.checkProtectedObjects(ops, protConfig, {\n allowedFqns,\n allowAll: Boolean(opts.allowAllProtected),\n });\n if (violations.length > 0) {\n console.error(protectedObjects.formatProtectionViolations(violations));\n process.exitCode = 1;\n return;\n }\n }\n\n printPlanReport(result.summary, script.summary, assessment, steps);\n\n // ── apply path ──────────────────────────────────────────────────────\n if (opts.apply) {\n const connectionName = opts.connection ?? profileConnection;\n if (!connectionName) {\n throw new Error(\n '--apply requires --connection <profile-name> or --profile <env> (supplies connection).',\n );\n }\n if (!opts.yes) {\n throw new Error(\n '--apply requires --yes. The CLI does not currently prompt interactively. Pass --yes to confirm.',\n );\n }\n if (assessment.blocked) {\n console.error(\n `Refusing to apply: safety classifier blocked the deploy (${assessment.blockReason}).`,\n );\n process.exitCode = 2;\n return;\n }\n\n // Approval gate (Team-tier): refuse to apply until N distinct\n // approvers have recorded approval tokens for this deploy id.\n if (opts.requireApprovals !== undefined && opts.requireApprovals !== false) {\n const required = Number(opts.requireApprovals) || 0;\n const allowed = opts.approver\n ? String(opts.approver)\n .split(',')\n .map((s: string) => s.trim())\n .filter(Boolean)\n : [];\n const deployId = String(opts.deployId ?? `${connectionName}:default`);\n const approvalsRoot = String(opts.approvalsRoot);\n const file = await approval.readApprovalFile(approvalsRoot, deployId);\n const outcome = approval.evaluateApprovalGate(\n { deployId, required, allowedApprovers: allowed },\n file.approvals,\n );\n if (!outcome.satisfied) {\n console.error(\n 'Approval gate blocked deploy: ' +\n (outcome.blockReason ?? 'gate not satisfied') +\n `. Record approvals with \\`ddt approval add ${deployId} --as <user>\\`.`,\n );\n process.exitCode = 2;\n return;\n }\n console.error(\n ` approvals: ${outcome.satisfiedBy.length}/${required} ` +\n `(${outcome.satisfiedBy.join(', ')})`,\n );\n }\n\n // AI preflight grader: ask the operator to type what they expect\n // this deploy to do, then let an AI compare that narrative to the\n // actual SQL + safety findings. Blocks deploy on `mismatch`.\n if (opts.aiPreflight) {\n const narrative = await readPreflightNarrative(opts.aiPreflightText);\n if (!narrative) {\n console.error(\n '--ai-preflight needs a narrative. Provide it inline via --ai-preflight-text or via stdin.',\n );\n process.exitCode = 2;\n return;\n }\n console.log('Grading deploy narrative with AI...');\n try {\n const findings = [\n ...assessment.unrecoverable.map((f) => ({\n code: String(f.code),\n fqn: f.fqn,\n reason: f.reason,\n })),\n ...assessment.destructive.map((f) => ({\n code: String(f.code),\n fqn: f.fqn,\n reason: f.reason,\n })),\n ...assessment.expensive.map((f) => ({\n code: String(f.code),\n fqn: f.fqn,\n reason: f.reason,\n })),\n ];\n const compareSummary = `added ${result.summary.added}, modified ${result.summary.modified}, removed ${result.summary.removed}, unchanged ${result.summary.unchanged}`;\n const verdict = await aiPreflight.gradePreflight(\n {\n narrative,\n compareSummary,\n safetyFindings: findings,\n diffSampleDdl: script.sql,\n target: `${result.target.label}@${connectionName ?? 'unknown'}`,\n },\n {\n completeFn: async (prompt) => {\n const r = await ai.complete([{ role: 'user', content: prompt }], {\n feature: 'ai-preflight',\n });\n return r.text;\n },\n },\n );\n console.log(` preflight verdict: ${verdict.verdict}`);\n if (verdict.reasoning) console.log(` preflight reasoning: ${verdict.reasoning}`);\n for (const d of verdict.discrepancies) console.log(` • ${d}`);\n\n const isBlocking =\n verdict.verdict === 'mismatch' ||\n (opts.strictAiPreflight && verdict.verdict === 'partial');\n if (isBlocking && !opts.confirmAfterPreflightMismatch) {\n console.error(\n `Refusing to apply: AI preflight returned \"${verdict.verdict}\". Re-run with --confirm-after-preflight-mismatch to override, or revise the narrative.`,\n );\n process.exitCode = 2;\n return;\n }\n if (verdict.parseFailed) {\n console.warn(\n ' preflight verdict could not be parsed — continuing without a clean alignment signal.',\n );\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error(\n `--ai-preflight failed: ${msg}. Configure an AI provider via \\`ddt ai status\\` or omit --ai-preflight.`,\n );\n process.exitCode = 2;\n return;\n }\n }\n\n // Lint gate — refuse --apply when the generated script trips an\n // ERROR-severity lint rule (L003 ADD NOT NULL no DEFAULT, L007\n // REFUSED placeholder). Opt out with --no-lint when you've\n // reviewed the script and want to proceed.\n if (opts.lint !== false) {\n const lint = lintSql(script.sql);\n if (lint.errorCount > 0) {\n console.error('');\n console.error(\n `Refusing to apply: lint gate caught ${lint.errorCount} ERROR-severity finding(s).`,\n );\n for (const f of lint.findings) {\n if (f.severity !== 'ERROR') continue;\n console.error(` ${f.rule} line ${f.line}: ${f.message}`);\n if (f.suggestion) console.error(` → ${f.suggestion}`);\n }\n console.error('');\n console.error('Resolve the findings or re-run with --no-lint to override.');\n process.exitCode = 2;\n return;\n }\n if (lint.warningCount > 0) {\n console.log(`Lint: ${lint.warningCount} warning(s) — proceeding.`);\n }\n }\n\n const profile = await getProfile(String(connectionName));\n const conn = createConnection(profile);\n const queryTag = resolveQueryTag(\n opts.queryTag,\n sourcePath,\n result.source.label,\n ctxProjectName,\n ctxProjectVersion,\n );\n if (queryTag) console.log(`Query tag: ${queryTag}`);\n try {\n await conn.connect();\n const executor = new DatabricksExecutor(conn, {\n ...(queryTag ? { queryTag } : {}),\n onStatement: (sql) => {\n const head = sql.split('\\n')[0]?.slice(0, 100) ?? '';\n console.log(` → ${head}${sql.length > 100 ? ' …' : ''}`);\n },\n });\n console.log('');\n console.log('--- APPLYING ---');\n const report = await executePlan(steps, executor, {\n rollbackOnFailure: opts.rollback !== false,\n requireReversible: !!opts.requireReversible,\n onStepStart: (step) => {\n console.log(`▶ ${step.objectType} ${step.fqn} — ${step.description}`);\n },\n onStepEnd: (r: StepResult) => {\n const tag =\n r.status === 'SUCCESS'\n ? '✓'\n : r.status === 'ROLLED_BACK'\n ? '↩'\n : r.status === 'FAILED'\n ? '✗'\n : r.status === 'SKIPPED'\n ? '-'\n : '?';\n console.log(\n ` ${tag} ${r.status}${r.durationMs ? ` (${r.durationMs}ms)` : ''}${r.error ? `: ${r.error}` : ''}`,\n );\n },\n });\n console.log('');\n console.log('--- DEPLOYMENT REPORT ---');\n console.log(`finalState: ${report.finalState}`);\n if (report.failedStepId) console.log(`failedStepId: ${report.failedStepId}`);\n if (report.preflightErrors?.length) {\n console.log('preflightErrors:');\n for (const e of report.preflightErrors) console.log(` ${e}`);\n }\n const manifestJson = JSON.stringify(\n buildDeployManifest(report, profile.auth.host),\n null,\n 2,\n );\n if (opts.manifest) {\n const mPath = path.resolve(String(opts.manifest));\n await fs.mkdir(path.dirname(mPath), { recursive: true });\n await fs.writeFile(mPath, manifestJson + '\\n', 'utf8');\n console.log(`Wrote deploy manifest → ${mPath}`);\n }\n\n // Target-side changelog table — best-effort. Failures are reported\n // (the deploy already succeeded) but never thrown.\n if (opts.changelog) {\n const catalog = opts.changelog === true ? undefined : String(opts.changelog);\n const r = await recordDeployChangelog(\n conn,\n report,\n result.source,\n result.target,\n manifestJson,\n '0.3.0',\n catalog ? { catalog } : {},\n );\n if (r.ok) {\n console.log(`Changelog: deploy_id=${r.entry.deployId} appended.`);\n } else {\n console.error(`Changelog write failed (deploy still completed): ${r.error}`);\n }\n }\n\n // Webhook notification — fire-and-forget POST with a small JSON\n // summary. Slack / Teams / generic JSON receivers all work.\n const webhookUrl = opts.webhook ?? process.env['DDT_NOTIFY_WEBHOOK'];\n if (webhookUrl) {\n try {\n await postWebhook(String(webhookUrl), {\n workspaceHost: profile.auth.host,\n source: result.source.label,\n target: result.target.label,\n finalState: report.finalState,\n failedStepId: report.failedStepId,\n stepsTotal: report.steps.length,\n stepsSucceeded: report.steps.filter((s) => s.status === 'SUCCESS').length,\n stepsFailed: report.steps.filter((s) => s.status === 'FAILED').length,\n });\n console.log(`Webhook notified → ${webhookUrl}`);\n } catch (err) {\n console.error(\n `Webhook POST failed (deploy still completed): ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n if (report.finalState === 'DIRTY') {\n console.error(\n 'DIRTY: rollback could not complete. Manual intervention required — see report above.',\n );\n process.exitCode = 1;\n } else if (report.finalState !== 'CLEAN_SUCCESS') {\n process.exitCode = 1;\n }\n\n if (opts.postDeployTests && report.finalState === 'CLEAN_SUCCESS') {\n const projectRoot = path.resolve(String(opts.postDeployTests));\n console.log('Running post-deploy DQ tests from ' + projectRoot + '...');\n const testFiles = await testFramework.discoverTests(projectRoot);\n if (testFiles.length === 0) {\n console.warn(\n ' POST_DEPLOY_DQ: no tests found under ' + projectRoot + '/tests/ — skipping.',\n );\n } else {\n const dqReport = await testFramework.runTestFiles(testFiles, conn);\n process.stdout.write(testFramework.renderTextReport(dqReport));\n if (dqReport.summary.blocking) {\n console.error(\n 'POST_DEPLOY_DQ_FAILED: ' +\n dqReport.summary.fail +\n ' fail / ' +\n dqReport.summary.error +\n ' error.' +\n (opts.manifest\n ? ' Recover: `ddt revert --manifest ' + String(opts.manifest) + '`'\n : ' Inspect tests/ and re-run after fixing data issues.'),\n );\n process.exitCode = 2;\n } else {\n console.log(\n ' POST_DEPLOY_DQ: ' +\n dqReport.summary.pass +\n '/' +\n dqReport.summary.total +\n ' pass.',\n );\n }\n }\n }\n } finally {\n await conn.disconnect();\n }\n return;\n }\n\n // ── dry-run path (default) ──────────────────────────────────────────\n // Colorize the script for terminal output so destructive lines and safety\n // banners are unmissable; ANSI is stripped in auto mode when stdout is\n // not a TTY (e.g. piped to a file or CI log).\n const colorMode = (opts.color as 'auto' | 'always' | 'never' | undefined) ?? 'auto';\n console.log('');\n console.log('--- MIGRATION SCRIPT ---');\n console.log(colorizeMigrationScript(script.sql, { mode: colorMode }));\n });\n attachRelatedOptions(cmd, [\n 'deployment.allowDropTable',\n 'deployment.allowDropColumn',\n 'deployment.allowUnrecoverableDrop',\n 'deployment.allowNarrowingTypes',\n 'deployment.allowTableRebuild',\n 'deployment.blockOnPossibleDataLoss',\n 'deployment.preserveTargetOnlyObjects',\n ]);\n return cmd;\n}\n\nfunction printPlanReport(\n diffSummary: { added: number; removed: number; modified: number; unchanged: number },\n scriptSummary: { destructive: number; refused: number },\n assessment: ReturnType<typeof safety.assess>,\n steps: ReturnType<typeof buildExecutionPlan>,\n): void {\n console.log('--- COMPARE SUMMARY ---');\n console.log(\n `+${diffSummary.added} -${diffSummary.removed} ~${diffSummary.modified} =${diffSummary.unchanged}` +\n (scriptSummary.destructive ? ` (destructive=${scriptSummary.destructive})` : '') +\n (scriptSummary.refused ? ` (refused=${scriptSummary.refused})` : ''),\n );\n console.log('');\n console.log('--- SAFETY ASSESSMENT ---');\n console.log(`unrecoverable=${assessment.unrecoverable.length}`);\n console.log(`destructive=${assessment.destructive.length}`);\n console.log(`expensive=${assessment.expensive.length}`);\n console.log(`warnings=${assessment.warnings.length}`);\n if (assessment.blocked) console.log(`BLOCKED: ${assessment.blockReason}`);\n console.log('');\n console.log('--- DEFAULT-SAFE PLAN ---');\n const reversible = steps.filter((st) => st.reverseSql).length;\n console.log(`${steps.length} step(s) planned (default-safe selection)`);\n console.log(`${reversible} step(s) reversible · ${steps.length - reversible} irreversible`);\n}\n\nasync function postWebhook(url: string, payload: unknown): Promise<void> {\n const isSlackOrTeams = /hooks\\.slack\\.com|webhook\\.office\\.com/.test(url);\n let body: string;\n if (isSlackOrTeams) {\n // Both Slack and Teams accept a simple { text: \"...\" } shape.\n const summary = payload as {\n finalState: string;\n target: string;\n stepsTotal: number;\n stepsSucceeded: number;\n stepsFailed: number;\n };\n body = JSON.stringify({\n text: `DDT publish → ${summary.target} · ${summary.finalState} · ${summary.stepsSucceeded}/${summary.stepsTotal} steps ok${summary.stepsFailed ? ` · ${summary.stepsFailed} failed` : ''}`,\n });\n } else {\n body = JSON.stringify(payload);\n }\n const res = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body,\n });\n if (!res.ok) {\n throw new Error(`HTTP ${res.status} ${res.statusText}`);\n }\n}\n\n// PD7.2 — parse `--variables KEY=VALUE,KEY=VALUE,...` using indexOf split\n// so a `=` inside the value (base64, JWT, connection-string fragments) is\n// preserved instead of being treated as a second delimiter. Mirrors the SDT\n// parsePublishVariables contract.\nexport function parseVariables(raw: unknown): Record<string, string> | undefined {\n if (!raw) return undefined;\n const out: Record<string, string> = {};\n for (const pair of String(raw).split(',')) {\n const eq = pair.indexOf('=');\n if (eq <= 0) continue;\n const k = pair.slice(0, eq).trim();\n const v = pair.slice(eq + 1).trim();\n if (k.length > 0) out[k] = v;\n }\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/**\n * Resolve the effective query tag. Honors an explicit `--query-tag`\n * flag value verbatim; otherwise auto-generates\n * `ddt:<projectName>@<projectVersion>:<unix-ms>` using the supplied\n * project context (pac manifest or .ddtproj). When projectName is\n * unknown, falls back to the source-path basename / sourceLabel; when\n * projectVersion is unknown the `@<projectVersion>` segment is omitted\n * so the tag remains valid. Returns undefined only when the user\n * explicitly passed `--query-tag ''`.\n */\nexport function resolveQueryTag(\n raw: unknown,\n sourcePath: string,\n sourceLabel: string,\n projectName: string | undefined,\n projectVersion: string | undefined,\n): string | undefined {\n if (raw !== undefined) {\n const s = String(raw).trim();\n return s.length === 0 ? undefined : s;\n }\n const fallback = sourcePath.endsWith('.ddtpac')\n ? path.basename(sourcePath, '.ddtpac')\n : sourceLabel;\n const base = projectName ?? fallback;\n const version = projectVersion ? `@${projectVersion}` : '';\n return `ddt:${base}${version}:${Date.now()}`;\n}\n\n/**\n * `ddt publish --restore-from-snapshot <batchId>` recovery path.\n *\n * Loads the batch from the registry, emits the restore SQL (DROP target +\n * CREATE … SHALLOW CLONE from snapshot, or a MANUAL hint row for\n * materialised / streaming objects), and either prints it (dry-run / no\n * --apply) or executes it against the live target (--apply --yes).\n *\n * Skips: pac freshness, compare, safety classifier, AI preflight, approval\n * gate, lint gate, manifest writing. Recovery is an emergency lever — the\n * gates that protect the forward path don't apply when we're restoring a\n * known-good snapshot the safety classifier itself authored.\n */\nasync function runRestoreFromSnapshot(opts: Record<string, unknown>): Promise<void> {\n const batchId = String(opts.restoreFromSnapshot);\n const registryDir = path.resolve(String(opts.snapshotDir ?? '.ddt/snapshots'));\n\n let batch: safety.SnapshotBatch;\n try {\n batch = await safety.readSnapshotBatch(registryDir, batchId);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error(`Snapshot batch \"${batchId}\" not found in ${registryDir}: ${msg}`);\n process.exitCode = 1;\n return;\n }\n\n const sqlLines = safety.emitRestoreFromSnapshotSql(batch);\n const sql = sqlLines.join('\\n');\n\n console.log(`Restoring from batch ${batch.batchId} (createdAt=${batch.createdAt})`);\n console.log(\n ` ${batch.entries.length} object(s) recorded; ${sqlLines.filter((l) => !l.startsWith('--')).length} statement(s) will run.`,\n );\n\n if (opts.out) {\n const out = path.resolve(String(opts.out));\n await fs.mkdir(path.dirname(out), { recursive: true });\n await fs.writeFile(out, sql + '\\n', 'utf8');\n console.log(`Wrote restore SQL → ${out}`);\n }\n\n // The DDT publish defaults --dry-run to true; recovery follows the same\n // convention: only --apply executes anything.\n if (!opts.apply) {\n const colorMode = (opts.color as 'auto' | 'always' | 'never' | undefined) ?? 'auto';\n process.stdout.write(colorizeMigrationScript(sql, { mode: colorMode }) + '\\n');\n return;\n }\n\n if (!opts.yes) {\n console.error(\n '--apply requires --yes (restore replaces target tables via DROP + SHALLOW CLONE).',\n );\n process.exitCode = 1;\n return;\n }\n if (!opts.connection) {\n console.error('--apply --restore-from-snapshot requires --connection <profile>.');\n process.exitCode = 1;\n return;\n }\n\n const profile = await getProfile(String(opts.connection));\n const conn = createConnection(profile);\n let executed = 0;\n let failed = 0;\n try {\n await conn.connect();\n for (const stmt of queryExecution.splitStatements(sql).map((s) => s.sql)) {\n try {\n await conn.executeRows(stmt);\n executed += 1;\n const head = stmt.split('\\n')[0]?.slice(0, 100) ?? '';\n console.log(' → ' + head + (stmt.length > 100 ? ' …' : ''));\n } catch (err) {\n failed += 1;\n const msg = err instanceof Error ? err.message : String(err);\n console.error(` [restore ${batch.batchId}] ${msg}\\n ${stmt}`);\n }\n }\n } finally {\n await conn.disconnect();\n }\n\n if (failed === 0) {\n console.log(`Restore complete. ${executed} statement(s) executed.`);\n } else {\n console.error(\n `Restore finished with failures: ${executed} ok, ${failed} failed. ` +\n `Inspect the snapshot tables under ${registryDir} and recover by hand.`,\n );\n process.exitCode = 1;\n }\n}\n\n/**\n * Read the AI-preflight narrative from --ai-preflight-text (preferred for CI)\n * or from stdin (interactive). Returns trimmed text, or undefined when no\n * narrative was supplied.\n */\nasync function readPreflightNarrative(inlineText: unknown): Promise<string | undefined> {\n if (typeof inlineText === 'string' && inlineText.trim().length > 0) {\n return inlineText.trim();\n }\n if (process.stdin.isTTY) {\n process.stdout.write(\n '\\n--ai-preflight is active. In one paragraph, describe what you expect this deploy to do.\\nEnd with an empty line (or Ctrl-D):\\n> ',\n );\n }\n process.stdin.setEncoding('utf8');\n let buffer = '';\n await new Promise<void>((resolve) => {\n const onData = (chunk: string): void => {\n buffer += chunk;\n if (/\\n\\s*\\n/.test(buffer)) {\n process.stdin.removeListener('data', onData);\n process.stdin.removeListener('end', onEnd);\n resolve();\n }\n };\n const onEnd = (): void => {\n process.stdin.removeListener('data', onData);\n resolve();\n };\n process.stdin.on('data', onData);\n process.stdin.on('end', onEnd);\n });\n const trimmed = buffer.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport {\n CompareEngine,\n PacSource,\n ProjectSource,\n ScriptGenerator,\n colorizeMigrationScript,\n mergeDeployOptions,\n renderHtmlReport,\n safety,\n loadProject,\n pac as pacNs,\n type CompareSource,\n type DeploymentProfile,\n} from '@ddt-tools/core';\nimport { addMappingFlags, buildMappingFromOptions } from '../util/mapping.js';\n\n/**\n * `ddt script` — generate a deploy SQL script the user can review or edit\n * before applying. Mirrors SqlPackage `/Action:Script` / SSDT's \"Generate\n * Script\" affordance.\n *\n * Output formats:\n * - sql (default): human-readable migration script with banner comments\n * - json: the raw CompareResult + safety assessment + per-statement\n * metadata, suitable for piping into a CI gate or a UI\n *\n * The script writer never touches the workspace. To apply, the user runs the\n * script through their own SQL client or calls `ddt publish --apply` (v0.4).\n */\nexport function scriptCommand(): Command {\n const cmd = new Command('script');\n cmd\n .description(\n 'Generate a deploy SQL script for source → target. Always offline — does not touch the workspace.',\n )\n .requiredOption('--source <path>', 'Source: .ddtproj or .ddtpac (the desired state).')\n .requiredOption('--target <path>', 'Target: .ddtproj or .ddtpac (the current state).')\n .option('-o, --out <path>', 'Write the script to <path>. Defaults to stdout.')\n .option('--format <fmt>', 'sql | json', 'sql')\n .option('--variables <kv>', 'Comma-separated KEY=VALUE pairs for $(VAR) substitution.')\n .option(\n '--profile <name>',\n 'VARSYNTAX.5 — look up `deploymentProfiles[<name>].variables` from the --source artifact (`.ddtproj` reads `project.deploymentProfiles`; `.ddtpac` reads `manifest.deploymentProfiles`) and substitute `$(VAR)` references at script-emission time. `--variables` overrides on key collision.',\n )\n .option('--ignore-case', 'Compare object FQNs case-insensitively.', false)\n .option('--banner <text>', 'Banner line prepended to the script.')\n .option('--report-html <path>', 'Also write a self-contained HTML compare-report to <path>.')\n .option(\n '--color <mode>',\n 'Color stdout: auto | always | never. Honors NO_COLOR / DDT_NO_COLOR env vars in auto mode. Files written via -o are never colorized.',\n 'auto',\n );\n addMappingFlags(cmd);\n cmd.action(async (opts) => {\n const format = String(opts.format ?? 'sql').toLowerCase();\n if (format !== 'sql' && format !== 'json') {\n throw new Error(`Unknown --format: ${opts.format}. Use sql or json.`);\n }\n const nameMapping = await buildMappingFromOptions(opts);\n const source = await sourceFor(String(opts.source), 'source');\n const target = await sourceFor(String(opts.target), 'target');\n const engine = new CompareEngine();\n const result = await engine.compare(source, target, {\n ignoreCase: !!opts.ignoreCase,\n ...(nameMapping ? { nameMapping } : {}),\n });\n\n const deployment = mergeDeployOptions().deployment;\n const cliVariables = parseVariables(opts.variables);\n\n // VARSYNTAX.5 — resolve --profile <name> from the --source artifact's\n // deploymentProfiles bag (if present), merge with --variables CLI\n // override (CLI wins on key collision). Also gather the project context\n // (name / version) so VARSYNTAX.3 built-ins (`$(DDT_PROFILE)`,\n // `$(DDT_PROJECT_NAME)`, `$(DDT_PROJECT_VERSION)`, …) auto-populate.\n let profileVariables: Record<string, string> | undefined;\n let ctxProjectName: string | undefined;\n let ctxProjectVersion: string | undefined;\n const sourcePath = String(opts.source);\n if (opts.profile || sourcePath.endsWith('.ddtproj') || sourcePath.endsWith('.ddtpac')) {\n try {\n if (sourcePath.endsWith('.ddtpac')) {\n const srcPac = await pacNs.readPac(sourcePath);\n ctxProjectName = srcPac.manifest.projectName;\n ctxProjectVersion = srcPac.manifest.projectVersion;\n if (opts.profile) {\n const block: DeploymentProfile | undefined =\n srcPac.manifest.deploymentProfiles?.[String(opts.profile)];\n if (!block) {\n const available = Object.keys(srcPac.manifest.deploymentProfiles ?? {});\n throw new Error(\n `--profile ${String(opts.profile)}: no deploymentProfile by that name in the --source pac manifest. ` +\n (available.length === 0\n ? 'The pac carries no deploymentProfiles (was it built before VARSYNTAX.2, or does the .ddtproj declare any?).'\n : `Available: ${available.join(', ')}.`),\n );\n }\n if (block.variables) profileVariables = { ...block.variables };\n }\n } else if (sourcePath.endsWith('.ddtproj')) {\n const loaded = await loadProject(sourcePath);\n ctxProjectName = loaded.project.name;\n ctxProjectVersion = loaded.project.version;\n if (opts.profile) {\n const block: DeploymentProfile | undefined =\n loaded.project.deploymentProfiles?.[String(opts.profile)];\n if (!block) {\n const available = Object.keys(loaded.project.deploymentProfiles ?? {});\n throw new Error(\n `--profile ${String(opts.profile)}: no deploymentProfile by that name in the --source .ddtproj. ` +\n (available.length === 0\n ? 'The project declares no deploymentProfiles.'\n : `Available: ${available.join(', ')}.`),\n );\n }\n if (block.variables) profileVariables = { ...block.variables };\n }\n }\n } catch (e) {\n if (opts.profile) throw e;\n }\n }\n const variables =\n profileVariables || cliVariables\n ? { ...(profileVariables ?? {}), ...(cliVariables ?? {}) }\n : undefined;\n\n const generator = new ScriptGenerator();\n const script = generator.generate(result, {\n deployment,\n variables,\n ...(opts.banner ? { banner: String(opts.banner) } : {}),\n context: {\n ...(opts.profile ? { profile: String(opts.profile) } : {}),\n ...(ctxProjectName ? { projectName: ctxProjectName } : {}),\n ...(ctxProjectVersion ? { projectVersion: ctxProjectVersion } : {}),\n },\n });\n const assessment = safety.assess(result);\n\n let payload: string;\n if (format === 'json') {\n payload = JSON.stringify(\n {\n source: result.source,\n target: result.target,\n summary: { ...result.summary, ...script.summary },\n safety: assessment,\n statements: script.statements,\n },\n null,\n 2,\n );\n } else {\n const header = [\n `-- ${assessment.blocked ? 'BLOCKED: ' + assessment.blockReason : 'Generated by ddt script'}`,\n `-- unrecoverable=${assessment.unrecoverable.length} destructive=${assessment.destructive.length} expensive=${assessment.expensive.length} warnings=${assessment.warnings.length}`,\n '',\n ].join('\\n');\n payload = header + script.sql;\n }\n\n if (opts.reportHtml) {\n const html = renderHtmlReport(result, {\n title: `Compare ${result.source.label} → ${result.target.label}`,\n safety: assessment,\n generatedSql: script.sql,\n });\n const htmlPath = path.resolve(String(opts.reportHtml));\n await fs.mkdir(path.dirname(htmlPath), { recursive: true });\n await fs.writeFile(htmlPath, html, 'utf8');\n console.error(`Wrote ${htmlPath} (${html.length} bytes).`);\n }\n\n if (opts.out) {\n const outPath = path.resolve(String(opts.out));\n await fs.mkdir(path.dirname(outPath), { recursive: true });\n await fs.writeFile(outPath, payload + (payload.endsWith('\\n') ? '' : '\\n'), 'utf8');\n console.error(`Wrote ${outPath} (${payload.length} bytes).`);\n } else {\n // Colorize stdout for SQL only — JSON stays raw so downstream tools can\n // parse it. ANSI escapes are stripped when stdout is not a TTY (auto mode).\n const colorMode = (opts.color as 'auto' | 'always' | 'never' | undefined) ?? 'auto';\n const rendered =\n format === 'sql' ? colorizeMigrationScript(payload, { mode: colorMode }) : payload;\n process.stdout.write(rendered);\n if (!rendered.endsWith('\\n')) process.stdout.write('\\n');\n }\n if (assessment.blocked) {\n process.exitCode = 2;\n }\n });\n return cmd;\n}\n\nasync function sourceFor(filePath: string, label: string): Promise<CompareSource> {\n return filePath.endsWith('.ddtpac')\n ? new PacSource(filePath, label)\n : new ProjectSource(filePath, label);\n}\n\nfunction parseVariables(raw: unknown): Record<string, string> | undefined {\n if (!raw) return undefined;\n const out: Record<string, string> = {};\n for (const pair of String(raw).split(',')) {\n const [k, v] = pair.split('=');\n if (k && v !== undefined) out[k.trim()] = v.trim();\n }\n return out;\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { importScript, loadProject, parseScript, type ParsedStatement } from '@ddt-tools/core';\n\n/**\n * `ddt import` — parse a SQL script and apply each DDL statement to a\n * `.ddtproj` tree, writing each into the canonical folder for its object\n * type (`catalogs/<cat>/schemas/<sch>/<type-folder>/<name>.sql`).\n *\n * Default mode is safe:\n * - Parses the whole script first; refuses to write anything if any\n * statement has hard errors. The user reviews the report, fixes the\n * script, and re-runs.\n * - Refuses to overwrite existing files. Pass `--force` to clobber.\n * - `--dry-run` shows the plan without writing.\n */\nexport function importCommand(): Command {\n const cmd = new Command('import');\n cmd\n .description(\n 'Parse a SQL script and write each DDL statement into the .ddtproj tree under its canonical folder.',\n )\n .requiredOption('--script <path>', 'Path to the SQL script to import.')\n .requiredOption('-p, --project <path>', 'Path to the .ddtproj file.')\n .option('--dry-run', 'Report what would be written without touching disk.', false)\n .option('--force', 'Overwrite existing files (default refuses on conflict).', false)\n .option(\n '--ignore-errors',\n 'Import classifiable statements even when others have errors. Default refuses on any error.',\n false,\n )\n .action(async (opts) => {\n const scriptPath = path.resolve(String(opts.script));\n const projectPath = path.resolve(String(opts.project));\n const sql = await fs.readFile(scriptPath, 'utf8');\n const parsed = parseScript(sql);\n\n // Up-front parse report — surfaces every error/warning verbatim.\n printParseReport(scriptPath, parsed);\n\n if (parsed.totalErrors > 0 && !opts.ignoreErrors) {\n console.error(\n `\\nRefusing to import: ${parsed.totalErrors} parse error(s) above. ` +\n `Fix the script and re-run, or pass --ignore-errors to import the clean statements.`,\n );\n process.exitCode = 2;\n return;\n }\n\n const loaded = await loadProject(projectPath);\n const result = await importScript(parsed, loaded, {\n dryRun: !!opts.dryRun,\n force: !!opts.force,\n });\n\n console.log('');\n const verb = opts.dryRun ? 'would write' : 'wrote';\n for (const item of result.imported) {\n const rel = path.relative(loaded.rootDir, item.targetPath);\n console.log(\n ` ${verb} ${item.statement.objectType} ${qualified(item.statement)} → ${rel}`,\n );\n }\n for (const item of result.skipped) {\n const head =\n item.statement.objectType && item.statement.fqn\n ? `${item.statement.objectType} ${qualified(item.statement)}`\n : `<unclassified statement at line ${item.statement.startLine}>`;\n console.log(` skip ${head} — ${item.reason}`);\n }\n console.log('');\n console.log(\n `Summary: ${result.imported.length} ${verb}, ${result.skipped.length} skipped, ` +\n `${parsed.totalErrors} errors, ${parsed.totalWarnings} warnings.`,\n );\n\n if (result.imported.length === 0 && result.skipped.length > 0) {\n process.exitCode = 1;\n }\n });\n return cmd;\n}\n\nfunction qualified(stmt: ParsedStatement): string {\n if (!stmt.fqn) return '<no fqn>';\n return [stmt.fqn.database, stmt.fqn.schema, stmt.fqn.name].filter(Boolean).join('.');\n}\n\nfunction printParseReport(scriptPath: string, parsed: ReturnType<typeof parseScript>): void {\n console.log(`Parsed ${parsed.statements.length} statement(s) from ${scriptPath}.`);\n if (parsed.totalErrors === 0 && parsed.totalWarnings === 0) {\n console.log('All statements classified cleanly.');\n return;\n }\n for (const stmt of parsed.statements) {\n if (stmt.errors.length === 0 && stmt.warnings.length === 0) continue;\n const head =\n stmt.objectType && stmt.fqn ? `${stmt.objectType} ${qualified(stmt)}` : '<unclassified>';\n console.log(`\\n[line ${stmt.startLine}–${stmt.endLine}] ${head}`);\n for (const e of stmt.errors) console.log(` ERROR: ${e}`);\n for (const w of stmt.warnings) console.log(` warning: ${w}`);\n }\n}\n","import path from 'node:path';\nimport { promises as fs } from 'node:fs';\nimport { Command } from 'commander';\nimport {\n AccountExtractor,\n catalog,\n createConnection,\n defaultExtractors,\n getProfile,\n pac,\n type DatabricksObject,\n} from '@ddt-tools/core';\n\n/**\n * `ddt extract` — read live workspace state into a `.ddtpac` artifact (or\n * onto disk as a project tree).\n *\n * Walks the configured scope (catalog / schema) via `AccountExtractor`,\n * hits the Statement Execution API + workspace REST for every UC object\n * type the registry knows about, and writes the result as either:\n * - `--output <dir>` → unzipped project tree under `<dir>/catalogs/...`\n * - `--out-pac <file>` → packed `.ddtpac` artifact\n *\n * The two modes are mutually exclusive; at least one is required.\n */\nexport function extractCommand(): Command {\n const cmd = new Command('extract');\n cmd\n .description(\n 'Extract live UC objects from a workspace into a project tree (--output) or a .ddtpac (--out-pac).',\n )\n .requiredOption(\n '-c, --connection <name>',\n 'Connection profile name (see `ddt connection list`).',\n )\n .option('--catalog <catalog>', 'Limit extraction to a single catalog.')\n .option('--schema <schema>', 'Limit extraction to a single schema (requires --catalog).')\n .option('--output <dir>', 'Write a project tree at <dir> (catalogs/.../<NAME>.sql).')\n .option('--out-pac <file>', 'Write a .ddtpac at <file> (artifact mode).')\n .option(\n '--project-name <name>',\n 'Project name stamped into manifest.json. Default: derived from --catalog or \"ExtractedProject\".',\n )\n .option(\n '--write-catalog-cache',\n 'Also write the extracted model to the EE1 catalog cache (.ddt/cache/<connection>/catalog.msgpack) so subsequent editor sessions have a populated cache without an extra `catalog refresh` round-trip.',\n false,\n )\n .option(\n '--use-catalog-cache',\n 'Read object metadata from the on-disk EE1 catalog cache instead of querying Databricks. Fast / offline — no live connection required. Writes a catalog-snapshot.json to the output dir. Requires a prior `ddt catalog refresh` or `ddt extract --write-catalog-cache` run.',\n false,\n )\n .action(async (opts) => {\n if (opts.useCatalogCache) {\n const out = path.resolve(String(opts.output ?? opts.outPac ?? '.'));\n await fs.mkdir(out, { recursive: true });\n const cache = new catalog.CatalogCache({ root: out, connection: String(opts.connection) });\n const snapshot = await cache.get();\n if (snapshot.catalogs.length === 0 && snapshot.fingerprint === null) {\n console.error(\n `No catalog cache found at ${cache.path}. Run \"ddt catalog refresh -c ${String(opts.connection)}\" or \"ddt extract --write-catalog-cache\" first.`,\n );\n process.exitCode = 1;\n return;\n }\n const outPath = path.join(out, '.ddt-cache', 'catalog-snapshot.json');\n await fs.mkdir(path.dirname(outPath), { recursive: true });\n await fs.writeFile(outPath, JSON.stringify(snapshot, null, 2));\n const objCount = snapshot.catalogs.flatMap((c) =>\n c.schemas.flatMap((s) => s.objects),\n ).length;\n console.log(\n `Loaded ${objCount} object(s) from catalog cache (${snapshot.catalogs.length} catalog(s)) → ${outPath}`,\n );\n console.log(\n `Cache was snapshotted at ${snapshot.snapshotAt}. Use \"ddt catalog refresh\" to update it.`,\n );\n return;\n }\n\n const hasOutput = !!opts.output;\n const hasPac = !!opts.outPac;\n if (!hasOutput && !hasPac) {\n throw new Error('Specify --output <dir> and/or --out-pac <file>.');\n }\n if (opts.schema && !opts.catalog) {\n throw new Error('--schema requires --catalog.');\n }\n\n const profile = await getProfile(String(opts.connection));\n const conn = createConnection(profile);\n try {\n await conn.connect();\n const accountExtractor = new AccountExtractor(defaultExtractors());\n const scope = {\n ...(opts.catalog ? { catalog: String(opts.catalog) } : {}),\n ...(opts.schema ? { schema: String(opts.schema) } : {}),\n };\n const t0 = Date.now();\n const model = await accountExtractor.extract(conn, scope);\n const elapsedSec = ((Date.now() - t0) / 1000).toFixed(1);\n console.log(\n `Extracted ${model.length} object(s) from ${profile.auth.host} in ${elapsedSec}s.`,\n );\n\n if (hasOutput) {\n const root = path.resolve(String(opts.output));\n await fs.mkdir(root, { recursive: true });\n await writeProjectTree(root, model);\n console.log(` → wrote project tree to ${root}`);\n }\n if (opts.writeCatalogCache) {\n // Honour --output as the cache root when set; otherwise --out-pac's\n // parent dir. Either way the cache lands at <root>/.ddt/cache/<conn>/.\n const cacheRoot = opts.output\n ? path.resolve(String(opts.output))\n : path.dirname(path.resolve(String(opts.outPac)));\n const snapshot = catalog.snapshotFromObjects(model, {\n connection: String(opts.connection),\n });\n const cache = new catalog.CatalogCache({\n root: cacheRoot,\n connection: String(opts.connection),\n });\n await cache.set(snapshot);\n console.log(\n ` → wrote catalog cache to ${cache.path} (${snapshot.catalogs.length} catalog(s), ${model.length} object(s)).`,\n );\n }\n if (hasPac) {\n const projectName =\n String(opts.projectName ?? '') ||\n (opts.catalog ? `${String(opts.catalog)}-extract` : 'ExtractedProject');\n const outPac = path.resolve(String(opts.outPac));\n await fs.mkdir(path.dirname(outPac), { recursive: true });\n await pac.writePac(outPac, {\n manifest: {\n formatVersion: 1,\n projectName,\n projectVersion: '0.0.0',\n scope: opts.schema\n ? { type: 'schema', catalog: String(opts.catalog), schema: String(opts.schema) }\n : opts.catalog\n ? { type: 'catalog', catalog: String(opts.catalog) }\n : { type: 'metastore' },\n targetPlatform: { platform: 'Databricks' },\n builtAt: new Date().toISOString(),\n builtBy: { name: 'ddt', version: '0.3.0' },\n objectCount: model.length,\n },\n model,\n source: {},\n checksums: pac.computeChecksums(model),\n });\n console.log(` → wrote .ddtpac to ${outPac}`);\n }\n } finally {\n await conn.disconnect();\n }\n });\n return cmd;\n}\n\nasync function writeProjectTree(root: string, model: DatabricksObject[]): Promise<void> {\n const { objectFilePath } = await import('@ddt-tools/core');\n for (const obj of model) {\n let target: string;\n try {\n target = objectFilePath(root, obj.objectType, {\n ...(obj.fqn.database ? { database: obj.fqn.database } : {}),\n ...(obj.fqn.schema ? { schema: obj.fqn.schema } : {}),\n name: obj.fqn.name,\n });\n } catch {\n // No folder mapping for this type — drop to a generic _unsorted/ bucket.\n target = path.join(root, '_unsorted', `${obj.objectType}__${obj.fqn.name}.sql`);\n }\n await fs.mkdir(path.dirname(target), { recursive: true });\n const ddl =\n 'ddl' in obj && typeof (obj as { ddl?: unknown }).ddl === 'string'\n ? ((obj as { ddl: string }).ddl as string)\n : `-- ${obj.objectType} ${[obj.fqn.database, obj.fqn.schema, obj.fqn.name].filter(Boolean).join('.')}\\n-- (no DDL captured — extractor returned model-only)`;\n await fs.writeFile(target, ddl.trim() + '\\n', 'utf8');\n }\n}\n","import { Command } from 'commander';\n\n/**\n * `ddt completion` — emit a shell completion script for bash / zsh / fish.\n * Pipe into your shell init: `ddt completion zsh > ~/.zsh/completions/_ddt`.\n *\n * Completion content is intentionally minimal — command names + the\n * known top-level flags. Subcommand-aware completion (i.e. completing\n * profile names after `ddt connection test`) would require a separate\n * shell helper that calls `ddt connection list`; out of scope.\n */\nexport function completionCommand(): Command {\n return new Command('completion')\n .description('Emit a shell completion script (bash | zsh | fish | powershell).')\n .argument('<shell>', 'bash | zsh | fish | powershell')\n .action((shell: string) => {\n const cmds = [\n 'connection',\n 'init',\n 'validate',\n 'compare',\n 'build',\n 'publish',\n 'script',\n 'import',\n 'extract',\n 'drift',\n 'refactor',\n 'format',\n 'completion',\n 'telemetry',\n 'license',\n ];\n switch (shell) {\n case 'bash':\n console.log(bashScript(cmds));\n return;\n case 'zsh':\n console.log(zshScript(cmds));\n return;\n case 'fish':\n console.log(fishScript(cmds));\n return;\n case 'powershell':\n case 'pwsh':\n console.log(powerShellScript(cmds));\n return;\n default:\n throw new Error(`Unsupported shell: ${shell}. Use bash | zsh | fish | powershell.`);\n }\n });\n}\n\nfunction bashScript(cmds: string[]): string {\n return `# ddt bash completion. Source from ~/.bashrc or drop in /etc/bash_completion.d/.\n_ddt() {\n local cur prev\n COMPREPLY=()\n cur=\"\\${COMP_WORDS[COMP_CWORD]}\"\n prev=\"\\${COMP_WORDS[COMP_CWORD-1]}\"\n if [[ $COMP_CWORD -eq 1 ]]; then\n COMPREPLY=( $(compgen -W \"${cmds.join(' ')}\" -- \"$cur\") )\n return 0\n fi\n}\ncomplete -F _ddt ddt\n`;\n}\n\nfunction zshScript(cmds: string[]): string {\n return `#compdef ddt\n_ddt() {\n local -a commands\n commands=(${cmds.map((c) => `'${c}:'`).join(' ')})\n _describe 'command' commands\n}\n_ddt \"$@\"\n`;\n}\n\nfunction fishScript(cmds: string[]): string {\n return cmds.map((c) => `complete -c ddt -f -n '__fish_use_subcommand' -a '${c}'`).join('\\n');\n}\n\nfunction powerShellScript(cmds: string[]): string {\n return `# ddt PowerShell completion. Add to your $PROFILE.\nRegister-ArgumentCompleter -Native -CommandName ddt -ScriptBlock {\n param($wordToComplete, $commandAst, $cursorPosition)\n $commands = @(${cmds.map((c) => `'${c}'`).join(', ')})\n $commands | Where-Object { $_ -like \"$wordToComplete*\" } | ForEach-Object {\n [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)\n }\n}\n`;\n}\n","import { Command } from 'commander';\nimport {\n CompareEngine,\n DbtManifestSource,\n InMemorySource,\n ProjectSource,\n AccountExtractor,\n createConnection,\n defaultExtractors,\n driftAnomaly,\n getProfile,\n type CompareSource,\n} from '@ddt-tools/core';\nimport { addMappingFlags, buildMappingFromOptions } from '../util/mapping.js';\nimport { attachRelatedOptions } from '../util/help-catalog.js';\n\nfunction driftWatchSubcommand(): Command {\n const sub = new Command('watch');\n sub\n .description(\n 'Poll a project against the live Unity Catalog on a fixed interval. Prints DRIFT_DETECTED events to stdout (or POSTs to --webhook) when the catalog diverges from the project.',\n )\n .requiredOption('--source <path>', 'Path to .ddtproj or .ddtpac')\n .requiredOption('--connection <name>', 'Connection profile name')\n .option('--catalog <catalog>', 'Limit drift check to a single catalog.')\n .option('--schema <schema>', 'Limit drift check to a single schema (requires --catalog).')\n .option('--interval <seconds>', 'Poll interval in seconds (min 5).', '60')\n .option(\n '--webhook <url>',\n 'POST drift events as JSON to this URL (Slack/Teams/generic receiver).',\n )\n .option('--format <fmt>', 'Output format: text | json.', 'text')\n .option(\n '--quiet',\n 'Suppress CLEAN status lines; emit only DRIFT_DETECTED and error events.',\n false,\n )\n .action(async (opts) => {\n const intervalSecs = Math.max(5, parseInt(String(opts.interval), 10) || 60);\n const format = String(opts.format) === 'json' ? 'json' : 'text';\n const webhookUrl = opts.webhook ? String(opts.webhook) : undefined;\n const quiet = !!opts.quiet;\n const sourcePath = String(opts.source);\n const scope = {\n ...(opts.catalog ? { catalog: String(opts.catalog) } : {}),\n ...(opts.schema ? { schema: String(opts.schema) } : {}),\n };\n\n const profile = await getProfile(String(opts.connection));\n const conn = createConnection(profile);\n await conn.connect();\n\n const src: CompareSource = sourcePath.endsWith('.ddtpac')\n ? await (async () => {\n const { PacSource } = await import('@ddt-tools/core');\n return new PacSource(sourcePath, 'source');\n })()\n : new ProjectSource(sourcePath, 'source');\n\n if (!quiet && format === 'text') {\n console.log(\n `drift watch: polling every ${intervalSecs}s — ${sourcePath} → ${profile.auth.host}`,\n );\n console.log('Press Ctrl+C to stop.');\n }\n\n const postToWebhook = async (event: Record<string, unknown>): Promise<void> => {\n if (!webhookUrl) return;\n try {\n const res = await fetch(webhookUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(event),\n });\n if (!res.ok && format === 'text') console.warn(`Webhook POST failed: HTTP ${res.status}`);\n } catch (err) {\n if (format === 'text')\n console.warn(`Webhook error: ${err instanceof Error ? err.message : String(err)}`);\n }\n };\n\n const pollOnce = async (): Promise<void> => {\n const ts = new Date().toISOString();\n try {\n const accountExtractor = new AccountExtractor(defaultExtractors());\n const liveObjs = await accountExtractor.extract(conn, scope);\n const live = new InMemorySource(liveObjs, { kind: 'live', label: profile.auth.host });\n const engine = new CompareEngine();\n const result = await engine.compare(src, live);\n const s = result.summary;\n const drifted = s.added + s.removed + s.modified;\n if (drifted > 0) {\n const event = {\n type: 'DRIFT_DETECTED',\n timestamp: ts,\n source: sourcePath,\n added: s.added,\n removed: s.removed,\n modified: s.modified,\n };\n if (format === 'json') process.stdout.write(JSON.stringify(event) + '\\n');\n else console.warn(`[${ts}] DRIFT_DETECTED +${s.added} -${s.removed} ~${s.modified}`);\n await postToWebhook(event);\n } else if (!quiet) {\n if (format === 'json')\n process.stdout.write(\n JSON.stringify({ type: 'CLEAN', timestamp: ts, source: sourcePath }) + '\\n',\n );\n else console.log(`[${ts}] clean`);\n }\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n if (format === 'json')\n process.stdout.write(\n JSON.stringify({ type: 'POLL_ERROR', timestamp: ts, error: message }) + '\\n',\n );\n else console.error(`[${ts}] poll error: ${message}`);\n }\n };\n\n await pollOnce();\n const timer = setInterval(() => {\n void pollOnce();\n }, intervalSecs * 1000);\n process.once('SIGINT', () => {\n clearInterval(timer);\n void conn.disconnect().then(() => process.exit(0));\n });\n await new Promise<void>(() => {});\n });\n return sub;\n}\n\n/**\n * `ddt drift` — refuse-on-drift CI gate. Compares a `.ddtproj` (or\n * `.ddtpac`) against a live target via the configured connection profile;\n * exits non-zero when the live state differs.\n *\n * Use it as a nightly cron / scheduled GitHub Action to catch unsanctioned\n * changes to prod.\n */\nexport function driftCommand(): Command {\n const cmd = new Command('drift');\n cmd\n .description(\n 'Refuse with non-zero exit when the live target has drifted from --source or a dbt manifest.',\n )\n .option('--source <path>', 'Source: .ddtproj or .ddtpac (required unless --vs-dbt-project).')\n .option(\n '--vs-dbt-project <path>',\n 'Compare a compiled dbt project (or target/manifest.json) against the live target. ' +\n 'Run `dbt compile` first. When set, --source is not required.',\n )\n .requiredOption('--connection <name>', 'Connection profile to extract live state from.')\n .option('--catalog <catalog>', 'Limit drift check to a single catalog.')\n .option('--schema <schema>', 'Limit drift check to a single schema (requires --catalog).')\n .option('--ignore-case', 'Compare object FQNs case-insensitively.', false)\n .option(\n '--allow-extras',\n 'Treat objects that exist on the target but not in source as OK (no drift).',\n false,\n )\n .option(\n '--anomalies',\n 'Also classify drift via the anomaly detector (new grants to `account users`, bypass-principal grants, owner changes, audit-column drops, mask removals, new bypass-named groups).',\n false,\n )\n .option(\n '--anomalies-only',\n 'Skip the simple drift summary and emit only the anomaly report. Implies --anomalies.',\n false,\n )\n .option(\n '--fail-on-anomaly <severity>',\n 'Exit non-zero when any anomaly at or above this severity fires. Values: critical | high | medium | low. Default: drift presence alone determines exit code.',\n );\n addMappingFlags(cmd);\n cmd.action(async (opts) => {\n if (!opts.source && !opts.vsDBtProject) {\n console.error('Provide either --source <path> or --vs-dbt-project <path>.');\n process.exitCode = 1;\n return;\n }\n const nameMapping = await buildMappingFromOptions(opts);\n const profile = await getProfile(String(opts.connection));\n const conn = createConnection(profile);\n try {\n await conn.connect();\n const accountExtractor = new AccountExtractor(defaultExtractors());\n const scope = {\n ...(opts.catalog ? { catalog: String(opts.catalog) } : {}),\n ...(opts.schema ? { schema: String(opts.schema) } : {}),\n };\n const liveObjs = await accountExtractor.extract(conn, scope);\n const live = new InMemorySource(liveObjs, { kind: 'live', label: profile.auth.host });\n const src: CompareSource = opts.vsDBtProject\n ? new DbtManifestSource(String(opts.vsDBtProject), `dbt:${opts.vsDBtProject}`)\n : String(opts.source).endsWith('.ddtpac')\n ? // PacSource via inline import to keep this command self-contained.\n await (async () => {\n const { PacSource } = await import('@ddt-tools/core');\n return new PacSource(String(opts.source), 'source');\n })()\n : new ProjectSource(String(opts.source), 'source');\n\n const engine = new CompareEngine();\n const result = await engine.compare(src, live, {\n ignoreCase: !!opts.ignoreCase,\n ...(nameMapping ? { nameMapping } : {}),\n });\n\n const s = result.summary;\n const drifted = s.added + s.modified + (opts.allowExtras ? 0 : s.removed);\n if (!opts.anomaliesOnly) {\n console.log(`Source: ${result.source.kind}:${result.source.label}`);\n console.log(`Target: ${result.target.kind}:${result.target.label}`);\n console.log(`Summary: +${s.added} -${s.removed} ~${s.modified} =${s.unchanged}`);\n console.log(`Drifted: ${drifted}` + (opts.allowExtras ? ' (extras allowed)' : ''));\n if (drifted > 0) {\n console.log('');\n console.log('Drift detected:');\n for (const o of result.objects) {\n if (o.kind === 'unchanged') continue;\n if (o.kind === 'removed' && opts.allowExtras) continue;\n const glyph =\n o.kind === 'added'\n ? '+ source-only'\n : o.kind === 'removed'\n ? '- target-only'\n : '~ modified';\n console.log(` ${glyph} ${o.identity.objectType} ${o.identity.fqn}`);\n }\n process.exitCode = 1;\n }\n }\n\n if (opts.anomalies || opts.anomaliesOnly) {\n const report = driftAnomaly.detectAnomalies(result);\n if (report.totalAnomalies === 0) {\n console.log('Anomaly scan: 0 findings.');\n } else {\n console.log('');\n console.log(`Anomaly scan: ${report.totalAnomalies} finding(s):`);\n for (const a of report.anomalies) {\n console.log(` [${a.severity}] ${a.category}: ${a.fqn} — ${a.reason}`);\n }\n const failOn = (opts.failOnAnomaly as string | undefined)?.toLowerCase();\n if (failOn && ['critical', 'high', 'medium', 'low'].includes(failOn)) {\n const failRank = driftAnomaly.anomalySeverityRank(\n failOn as driftAnomaly.AnomalySeverity,\n );\n const triggered = report.anomalies.some(\n (a) => driftAnomaly.anomalySeverityRank(a.severity) <= failRank,\n );\n if (triggered) process.exitCode = 1;\n }\n }\n }\n } finally {\n await conn.disconnect();\n }\n });\n attachRelatedOptions(cmd, [\n 'compare.ignoreCase',\n 'compare.ignoreComments',\n 'compare.ignoreFormattingDifferences',\n 'compare.excludeObjectTypes',\n ]);\n cmd.addCommand(driftWatchSubcommand());\n return cmd;\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { loadProject, discoverObjectFiles } from '@ddt-tools/core';\nimport {\n FORMAT_STYLE_PRESET_NAMES,\n format as formatV2,\n getFormatPreset,\n isFormatStylePreset,\n mergeFormatStyle,\n} from '@ddt-tools/core/format';\nimport type { FormatDiagnostic, FormatStyle } from '@ddt-tools/core/format';\n\n/**\n * `ddt format` — opinionated SQL formatter for project files.\n *\n * The formatter is intentionally simple and platform-agnostic:\n * - Uppercase reserved keywords (CREATE / TABLE / VIEW / SELECT / ...).\n * - Trim trailing whitespace.\n * - Collapse 3+ blank lines to 2.\n * - Ensure file ends with exactly one newline.\n *\n * It does NOT try to be a full SQL pretty-printer (indenting clauses,\n * aligning column lists). Real prettifying requires a dialect-aware\n * parser; users can wire `sql-formatter` in their editor for that.\n */\nconst RESERVED = new Set<string>([\n 'CREATE',\n 'OR',\n 'REPLACE',\n 'REFRESH',\n 'STREAMING',\n 'MATERIALIZED',\n 'TEMPORARY',\n 'EXTERNAL',\n 'MANAGED',\n 'TABLE',\n 'VIEW',\n 'CATALOG',\n 'SCHEMA',\n 'FUNCTION',\n 'VOLUME',\n 'PIPELINE',\n 'CONNECTION',\n 'SHARE',\n 'RECIPIENT',\n 'WAREHOUSE',\n 'CLUSTER',\n 'ALTER',\n 'DROP',\n 'TRUNCATE',\n 'COMMENT',\n 'GRANT',\n 'REVOKE',\n 'USE',\n 'SELECT',\n 'FROM',\n 'WHERE',\n 'GROUP',\n 'BY',\n 'ORDER',\n 'LIMIT',\n 'OFFSET',\n 'JOIN',\n 'INNER',\n 'LEFT',\n 'RIGHT',\n 'OUTER',\n 'CROSS',\n 'ON',\n 'AS',\n 'AND',\n 'OR',\n 'NOT',\n 'IN',\n 'IS',\n 'NULL',\n 'TRUE',\n 'FALSE',\n 'BETWEEN',\n 'LIKE',\n 'EXISTS',\n 'INSERT',\n 'INTO',\n 'UPDATE',\n 'SET',\n 'DELETE',\n 'MERGE',\n 'USING',\n 'WHEN',\n 'MATCHED',\n 'WITH',\n 'CASE',\n 'THEN',\n 'ELSE',\n 'END',\n 'UNION',\n 'ALL',\n 'DISTINCT',\n 'PARTITIONED',\n 'CLUSTERED',\n 'TBLPROPERTIES',\n 'LOCATION',\n 'USING',\n 'OPTIONS',\n 'PRIMARY',\n 'FOREIGN',\n 'KEY',\n 'CONSTRAINT',\n 'REFERENCES',\n 'UNIQUE',\n 'CHECK',\n 'IF',\n 'CASCADE',\n 'RESTRICT',\n // Common Databricks-side types\n 'BIGINT',\n 'INT',\n 'SMALLINT',\n 'TINYINT',\n 'FLOAT',\n 'DOUBLE',\n 'DECIMAL',\n 'BOOLEAN',\n 'STRING',\n 'DATE',\n 'TIMESTAMP',\n 'TIMESTAMP_NTZ',\n 'BINARY',\n 'ARRAY',\n 'MAP',\n 'STRUCT',\n 'VARIANT',\n 'INTERVAL',\n]);\n\nexport function formatCommand(): Command {\n const cmd = new Command('format');\n cmd\n .description(\n 'Format every .sql under a .ddtproj — uppercase reserved keywords + tidy whitespace.',\n )\n .requiredOption('-p, --project <path>', 'Path to the .ddtproj file.')\n .option('--check', 'Report files that would change without writing.', false)\n .option(\n '--engine <v>',\n 'Formatter engine: \"legacy\" (default) | \"v2\" (new tokenizer-based engine with refuse-on-invalid).',\n 'legacy',\n )\n .option(\n '--dbt',\n 'Force dbt-mode on (v2 engine only): pre-mask {{ ... }} / {% ... %} Jinja blocks so they survive byte-for-byte across the format pass. Default: auto-detect.',\n )\n .option(\n '--no-dbt',\n 'Force dbt-mode off (v2 engine only): feed Jinja text directly to the formatter (almost always wrong on dbt models).',\n )\n .option(\n '--style <preset>',\n `Apply a named layout preset before any project-level overrides (v2 engine only): ${FORMAT_STYLE_PRESET_NAMES.join(' | ')}. compact = single-line where possible (120-col, 0 blank lines, sameLine closers); expanded = each clause on its own line (100-col, 1 blank line, aligned closers); wide = expanded with maxLineWidth 140 for ultrawide terminals.`,\n )\n .action(async (opts) => {\n const engine = String(opts.engine ?? 'legacy').toLowerCase();\n if (engine !== 'legacy' && engine !== 'v2') {\n throw new Error(`Unknown --engine: ${opts.engine}. Use \"legacy\" or \"v2\".`);\n }\n // DBTC.4 — --dbt / --no-dbt resolves to FormatStyle.experimental.dbtMode\n // (v2 engine only). Commander's --no-dbt yields opts.dbt === false.\n const dbtMode: 'auto' | 'on' | 'off' | undefined =\n opts.dbt === true ? 'on' : opts.dbt === false ? 'off' : undefined;\n let preset: FormatStyle | undefined;\n if (opts.style) {\n const styleName = String(opts.style).toLowerCase();\n if (!isFormatStylePreset(styleName)) {\n throw new Error(\n `--style must be one of: ${FORMAT_STYLE_PRESET_NAMES.join(', ')}. Got '${opts.style}'.`,\n );\n }\n preset = getFormatPreset(styleName);\n }\n const dbtOverride: FormatStyle = dbtMode ? { experimental: { dbtMode } } : {};\n const v2Style: FormatStyle | undefined =\n preset || dbtMode ? mergeFormatStyle(preset, dbtOverride) : undefined;\n const loaded = await loadProject(String(opts.project));\n const files = await discoverObjectFiles(loaded);\n const sqlFiles = files.filter((f) => f.endsWith('.sql'));\n let changed = 0;\n let refused = 0;\n for (const f of sqlFiles) {\n const before = await fs.readFile(f, 'utf8');\n const rel = path.relative(loaded.rootDir, f);\n\n if (engine === 'v2') {\n const result = formatV2(before, v2Style);\n if (result.refused) {\n const errs: FormatDiagnostic[] = result.diagnostics.filter(\n (d) => d.severity === 'ERROR',\n );\n console.error(`refused ${rel} — ${errs.length} error(s):`);\n for (const d of errs) {\n console.error(` L${d.line}:${d.column} [${d.code}] ${d.message}`);\n }\n refused++;\n continue;\n }\n if (result.changed) {\n changed++;\n if (opts.check) {\n console.log(`would change ${rel}`);\n } else {\n await fs.writeFile(f, result.output, 'utf8');\n console.log(`formatted ${rel}`);\n }\n }\n continue;\n }\n\n // Legacy engine.\n const after = formatSql(before);\n if (after !== before) {\n changed++;\n if (opts.check) {\n console.log(`would change ${rel}`);\n } else {\n await fs.writeFile(f, after, 'utf8');\n console.log(`formatted ${rel}`);\n }\n }\n }\n console.log('');\n const verb = opts.check ? 'would change' : 'changed';\n const refusedNote = refused > 0 ? ` (${refused} refused on errors)` : '';\n console.log(`Summary: ${changed} of ${sqlFiles.length} file(s) ${verb}${refusedNote}.`);\n if (opts.check && changed > 0) process.exitCode = 1;\n if (refused > 0) process.exitCode = 1;\n });\n return cmd;\n}\n\n/**\n * Token-aware reformat. Skips strings + comments + quoted identifiers,\n * upcases reserved keywords elsewhere, then normalizes whitespace.\n */\nexport function formatSql(sql: string): string {\n const out: string[] = [];\n let i = 0;\n const n = sql.length;\n while (i < n) {\n const c = sql[i];\n const next = sql[i + 1];\n\n // Comments.\n if (c === '-' && next === '-') {\n while (i < n && sql[i] !== '\\n') {\n out.push(sql[i]!);\n i++;\n }\n continue;\n }\n if (c === '/' && next === '*') {\n out.push('/*');\n i += 2;\n while (i < n && !(sql[i] === '*' && sql[i + 1] === '/')) {\n out.push(sql[i]!);\n i++;\n }\n if (i < n) {\n out.push('*/');\n i += 2;\n }\n continue;\n }\n\n // String literals.\n if (c === \"'\" || c === '\"' || c === '`') {\n const quote = c;\n out.push(quote);\n i++;\n while (i < n) {\n const cc = sql[i]!;\n if (cc === quote && sql[i + 1] === quote) {\n out.push(cc);\n out.push(sql[i + 1] ?? '');\n i += 2;\n continue;\n }\n out.push(cc);\n i++;\n if (cc === quote) break;\n }\n continue;\n }\n\n // Identifier-ish token.\n if (c && /[A-Za-z_]/.test(c)) {\n let j = i;\n while (j < n && /[A-Za-z0-9_]/.test(sql[j]!)) j++;\n const word = sql.slice(i, j);\n out.push(RESERVED.has(word.toUpperCase()) ? word.toUpperCase() : word);\n i = j;\n continue;\n }\n\n if (c !== undefined) out.push(c);\n i++;\n }\n let result = out.join('');\n // Trim trailing whitespace on each line.\n result = result\n .split('\\n')\n .map((l) => l.replace(/[ \\t]+$/g, ''))\n .join('\\n');\n // Collapse 3+ blank lines to 2.\n result = result.replace(/\\n{3,}/g, '\\n\\n');\n // Ensure exactly one trailing newline.\n result = result.replace(/\\n*$/, '\\n');\n return result;\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport {\n lintSql,\n lintRules,\n loadRulePacks,\n loadRulePacksFromDir,\n compileRulePacks,\n RULE_PACK_DIR,\n dbtCode,\n interop,\n type LintResult,\n type LintRule,\n} from '@ddt-tools/core';\n\n/** DBTC.4 — auto-detect dbt-mode in the lint surface. */\nconst JINJA_OPENER = /\\{\\{|\\{%/;\n\n/**\n * `ddt lint` — scan a SQL script for risky patterns before you run it.\n * Atlas-style migration linting. Rules cover L001-L032 platform-agnostic\n * + D001-D005 Databricks-specific.\n */\nexport function lintCommand(): Command {\n const cmd = new Command('lint');\n cmd\n .description(\n 'Lint a SQL script for risky deploy patterns. Exits non-zero on any ERROR-severity finding.',\n )\n .option('--script <path>', 'Path to the SQL script to lint (default: read stdin).')\n .option(\n '--json',\n 'Emit JSON instead of human-readable output. (Alias for --format json.)',\n false,\n )\n .option(\n '--format <fmt>',\n 'Output format: text | json | markdown | sarif. sarif emits SARIF 2.1.0 for GitHub code-scanning / Azure DevOps. Default text.',\n 'text',\n )\n .option('--rules', 'Print the rule list and exit.', false)\n .option(\n '--max-warnings <n>',\n 'Fail when warning count exceeds <n>. 0 = any warning fails. Default: unbounded.',\n '-1',\n )\n .option(\n '--dbt',\n 'Force dbt-mode on: pre-mask {{ ... }} / {% ... %} Jinja blocks before linting so the lint rules see a tidy SQL document. Default: auto-detect.',\n )\n .option(\n '--no-dbt',\n 'Force dbt-mode off: feed Jinja text directly to the lint rules (almost always wrong on dbt models).',\n )\n .option(\n '--rules-dir <path>',\n `Directory holding custom rule-pack JSON files (RULEPACK.1). Default: <cwd>/${RULE_PACK_DIR}.`,\n )\n .option(\n '--no-custom-rules',\n 'Skip loading customer-defined rule packs; lint with the built-in catalog only.',\n )\n .action(async (opts) => {\n // RULEPACK.1 — customer-defined rules merge into the built-in catalog.\n // Invalid definitions are reported to stderr but never abort the lint.\n const extraRules = await loadCustomRules(opts);\n\n if (opts.rules) {\n for (const r of lintRules(extraRules)) {\n console.log(`${r.id.padEnd(6)} ${r.severity.padEnd(8)} ${r.description}`);\n }\n return;\n }\n const rawSql = opts.script\n ? await fs.readFile(String(opts.script), 'utf8')\n : await readStdin();\n // DBTC.4 — pre-mask Jinja so {{ ref(...) }} doesn't trip lint rules\n // that scan for keyword shapes. Default auto-detects on a Jinja\n // opener; --dbt / --no-dbt force the choice.\n const dbtActive = opts.dbt === true || (opts.dbt !== false && JINJA_OPENER.test(rawSql));\n const sql = dbtActive ? dbtCode.maskJinja(rawSql).masked : rawSql;\n const result = lintSql(sql, extraRules);\n\n const fmt = opts.json ? 'json' : String(opts.format ?? 'text').toLowerCase();\n if (fmt === 'json') {\n console.log(JSON.stringify(result, null, 2));\n } else if (fmt === 'markdown') {\n console.log(renderMarkdown(result));\n } else if (fmt === 'sarif') {\n const uri = opts.script ? String(opts.script) : '<stdin>';\n console.log(JSON.stringify(interop.lintResultToSarif(result, uri), null, 2));\n } else if (fmt === 'text') {\n for (const f of result.findings) {\n const tag = f.severity === 'ERROR' ? '✗' : f.severity === 'WARNING' ? '⚠' : 'ℹ';\n console.log(`${tag} ${f.rule} line ${f.line} ${f.severity}`);\n console.log(` ${f.message}`);\n if (f.suggestion) console.log(` → ${f.suggestion}`);\n console.log(` ${f.statement.split('\\n')[0]?.slice(0, 100) ?? ''}`);\n console.log('');\n }\n console.log(\n `Summary: ${result.errorCount} error(s), ${result.warningCount} warning(s), ${result.infoCount} info.`,\n );\n } else {\n throw new Error(`Unknown --format \"${opts.format}\". Use text | json | markdown | sarif.`);\n }\n\n const maxWarnings = parseInt(String(opts.maxWarnings), 10);\n if (result.errorCount > 0) {\n process.exitCode = 1;\n } else if (maxWarnings >= 0 && result.warningCount > maxWarnings) {\n process.exitCode = 1;\n }\n });\n return cmd;\n}\n\n/**\n * RULEPACK.1 — load + compile custom rule packs based on the CLI flags.\n * `--no-custom-rules` disables; `--rules-dir <dir>` reads packs from an\n * explicit directory instead of the default `<cwd>/.ddt/rules`. Skipped\n * (invalid) definitions are reported to stderr but never abort the lint.\n */\nasync function loadCustomRules(opts: {\n customRules?: boolean;\n rulesDir?: string;\n}): Promise<LintRule[]> {\n if (opts.customRules === false) return [];\n const result = opts.rulesDir\n ? await loadRulePacksFromDir(path.resolve(String(opts.rulesDir)))\n : await loadRulePacks(process.cwd());\n for (const s of result.skipped) {\n console.error(\n `⚠ rule pack: skipped ${s.id ? `rule '${s.id}'` : 'file'} in ${s.file} — ${s.reason}`,\n );\n }\n return compileRulePacks(result.packs);\n}\n\nfunction renderMarkdown(result: LintResult): string {\n const lines: string[] = [];\n lines.push('# Lint findings');\n lines.push('');\n lines.push(\n `**Summary**: ${result.errorCount} error(s), ${result.warningCount} warning(s), ${result.infoCount} info.`,\n );\n lines.push('');\n if (result.findings.length === 0) {\n lines.push('_(no findings)_');\n return lines.join('\\n');\n }\n lines.push('| Severity | Rule | Line | Message |');\n lines.push('| --- | --- | ---: | --- |');\n for (const f of result.findings) {\n const sev =\n f.severity === 'ERROR' ? '🛑 ERROR' : f.severity === 'WARNING' ? '⚠ WARN' : 'ℹ INFO';\n const msg = f.message.replace(/\\|/g, '\\\\|');\n lines.push(`| ${sev} | \\`${f.rule}\\` | ${f.line} | ${msg} |`);\n }\n lines.push('');\n for (const f of result.findings) {\n lines.push(`### ${f.rule} (${f.severity}) — line ${f.line}`);\n lines.push('');\n lines.push(f.message);\n if (f.suggestion) {\n lines.push('');\n lines.push(`> ${f.suggestion}`);\n }\n lines.push('');\n lines.push('```sql');\n lines.push(f.statement.split('\\n')[0]?.slice(0, 200) ?? '');\n lines.push('```');\n lines.push('');\n }\n return lines.join('\\n');\n}\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const c of process.stdin) chunks.push(c as Buffer);\n return Buffer.concat(chunks).toString('utf8');\n}\n","import { promises as fs } from 'node:fs';\nimport { execSync } from 'node:child_process';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport {\n loadProject,\n parseProjectModel,\n renderDocsReport,\n renderErdMarkdown,\n renderErd3dHtml,\n pac,\n ai,\n comments,\n type DatabricksObject,\n} from '@ddt-tools/core';\nimport { buildDocsPublishPlan, renderDocsWorkflowYaml, searchDocs } from '@ddt-tools/core/docs';\n\n/**\n * `ddt docs` — auto-generate HTML schema docs from a `.ddtproj` or\n * `.ddtpac`. dbt-docs-style: catalog → schema → object navigation with\n * per-object detail panels.\n */\nexport function docsCommand(): Command {\n const cmd = new Command('docs');\n cmd\n .description('Generate HTML schema docs from a .ddtproj or .ddtpac.')\n .requiredOption('--source <path>', '.ddtproj or .ddtpac to document.')\n .option('-o, --out <path>', 'Output HTML file path (omit when using --augment-comments).')\n .option('--title <text>', 'Page title.', 'Schema docs')\n .option(\n '--augment-comments',\n 'Skip HTML rendering. Instead, call the configured AI provider to suggest comments for every empty COMMENT slot and emit COMMENT ON / ALTER COLUMN SQL.',\n false,\n )\n .option(\n '--augment-out <path>',\n 'When --augment-comments is set, write the script here. Default ./augment-comments.sql.',\n )\n .option(\n '--augment-max-calls <n>',\n 'When --augment-comments is set, cap AI calls. Default unbounded.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--augment-max-length <n>',\n 'When --augment-comments is set, cap suggestion length in characters. Default 200.',\n (v) => parseInt(v, 10),\n )\n .action(\n async (opts: {\n source: string;\n out?: string;\n title?: string;\n augmentComments?: boolean;\n augmentOut?: string;\n augmentMaxCalls?: number;\n augmentMaxLength?: number;\n }) => {\n const model = await loadModel(String(opts.source));\n\n if (opts.augmentComments) {\n const targets = comments.findMissingComments(model);\n if (targets.length === 0) {\n console.log('No missing COMMENT slots found. Nothing to augment.');\n return;\n }\n console.log(`Found ${targets.length} missing comment slot(s). Calling AI provider…`);\n const suggestions = await comments.augmentComments(targets, {\n completeFn: async (prompt: string) => {\n const r = await ai.complete([{ role: 'user', content: prompt }], {\n feature: 'docs.augment-comments',\n });\n return r.text;\n },\n ...(opts.augmentMaxLength ? { maxCommentLength: opts.augmentMaxLength } : {}),\n ...(opts.augmentMaxCalls ? { maxCalls: opts.augmentMaxCalls } : {}),\n });\n const sql = comments.renderAlterCommentScript(suggestions);\n const accepted = suggestions.filter((s) => s.suggestion.trim().length > 0).length;\n const uncertain = suggestions.length - accepted;\n const outPath = opts.augmentOut\n ? path.resolve(String(opts.augmentOut))\n : path.resolve('augment-comments.sql');\n await fs.mkdir(path.dirname(outPath), { recursive: true });\n await fs.writeFile(outPath, sql, 'utf8');\n console.log(\n `Wrote ${outPath} (${accepted} suggestion(s), ${uncertain} flagged for review).`,\n );\n return;\n }\n\n if (!opts.out) {\n throw new Error('Missing --out. Required unless --augment-comments is set.');\n }\n const html = renderDocsReport(model, { title: String(opts.title ?? 'Schema docs') });\n const outPath = path.resolve(String(opts.out));\n await fs.mkdir(path.dirname(outPath), { recursive: true });\n await fs.writeFile(outPath, html, 'utf8');\n console.log(`Wrote ${outPath} (${html.length} bytes, ${model.length} objects).`);\n },\n );\n\n cmd\n .command('build')\n .description(\n 'Build the HTML schema docs site (alias for the parent command with --out default).',\n )\n .requiredOption('--source <path>', '.ddtproj or .ddtpac to document.')\n .option('-o, --out <path>', 'Output HTML file path.', 'dist/docs/index.html')\n .option('--title <text>', 'Page title.', 'Schema docs')\n .action(async (opts: { source: string; out: string; title?: string }) => {\n const model = await loadModel(String(opts.source));\n const html = renderDocsReport(model, { title: String(opts.title ?? 'Schema docs') });\n const outPath = path.resolve(String(opts.out));\n await fs.mkdir(path.dirname(outPath), { recursive: true });\n await fs.writeFile(outPath, html, 'utf8');\n console.log(`Wrote ${outPath} (${html.length} bytes, ${model.length} objects).`);\n });\n\n cmd\n .command('publish')\n .description('Publish the generated docs site to a gh-pages branch.')\n .requiredOption('--site <path>', 'Path to the built docs site directory (e.g. dist/docs).')\n .option('--branch <name>', 'Target branch name.', 'gh-pages')\n .option('--remote <name>', 'Git remote name.', 'origin')\n .option('--message <text>', 'Commit message.', 'chore(docs): deploy schema docs [skip ci]')\n .option('--dry-run', 'Print the commands that would be executed without running them.', false)\n .option('--emit-workflow <path>', 'Write a GitHub Actions workflow YAML template to this path.')\n .action(async (opts) => {\n if (opts.emitWorkflow) {\n const yaml = renderDocsWorkflowYaml({ branch: opts.branch, trigger: 'main' });\n const wPath = path.resolve(String(opts.emitWorkflow));\n await fs.mkdir(path.dirname(wPath), { recursive: true });\n await fs.writeFile(wPath, yaml, 'utf8');\n console.log(`Wrote workflow template → ${wPath}`);\n return;\n }\n const plan = buildDocsPublishPlan({\n siteDir: path.resolve(String(opts.site)),\n branch: opts.branch,\n remote: opts.remote,\n message: opts.message,\n });\n for (const step of plan.steps) {\n console.log(` ${step.description}`);\n if (opts.dryRun) {\n console.log(` [dry-run] ${step.command}`);\n } else {\n execSync(step.command, { stdio: 'inherit' });\n }\n }\n if (!opts.dryRun) console.log(`Done — site pushed to ${plan.remote}/${plan.branch}.`);\n });\n\n cmd\n .command('search')\n .description('Search object names, comments, and column names in a .ddtproj or .ddtpac.')\n .argument('<query>', 'Search query string.')\n .requiredOption('--source <path>', '.ddtproj or .ddtpac to search.')\n .option('-n, --max-results <n>', 'Maximum number of results to return.', (v) => parseInt(v, 10))\n .action(async (query: string, opts: { source: string; maxResults?: number }) => {\n const model = await loadModel(String(opts.source));\n const hits = searchDocs(model as Parameters<typeof searchDocs>[0], query, {\n maxResults: opts.maxResults,\n });\n if (hits.length === 0) {\n console.log(`No results for \"${query}\".`);\n return;\n }\n for (const hit of hits) {\n console.log(`[${hit.score}] ${hit.objectFqn} (${hit.objectType}) — ${hit.field}`);\n console.log(` ${hit.snippet}`);\n }\n console.log(`\\n${hits.length} result(s) for \"${query}\".`);\n });\n\n return cmd;\n}\n\n/**\n * `ddt erd` — auto-generate an ER diagram from a `.ddtproj` or `.ddtpac`.\n *\n * Output format defaults to Mermaid Markdown for back-compat. Pass\n * `--format html3d` (or write to a `.html` file) to emit the interactive\n * 3D WebGL viewer — a single self-contained HTML file you can open in\n * any browser. The 3D viewer lays out schemas as horizontal planes with\n * tables as boxes and FKs as bezier curves; supports click-to-focus,\n * search, 2D toggle, and full orbit/pan/zoom. See DIAG-1 spec.\n */\nexport function erdCommand(): Command {\n const cmd = new Command('erd');\n cmd\n .description(\n 'Generate an ER diagram (Mermaid Markdown or interactive 3D HTML) from a .ddtproj or .ddtpac.',\n )\n .requiredOption('--source <path>', '.ddtproj or .ddtpac to diagram.')\n .requiredOption(\n '-o, --out <path>',\n 'Output file path. Format inferred from extension (.md → mermaid, .html → html3d) unless --format is given.',\n )\n .option('--title <text>', 'Diagram title.', 'Schema ER diagram')\n .option(\n '--format <fmt>',\n 'Output format: mermaid | html3d. Default: inferred from --out extension, falling back to mermaid.',\n )\n .action(async (opts: { source: string; out: string; title?: string; format?: string }) => {\n const model = await loadModel(String(opts.source));\n const title = String(opts.title ?? 'Schema ER diagram');\n const fmt = resolveErdFormat(String(opts.out), opts.format);\n let content: string;\n if (fmt === 'html3d') {\n content = renderErd3dHtml(model, { title });\n } else {\n content = renderErdMarkdown(model, title);\n }\n const outPath = path.resolve(String(opts.out));\n await fs.mkdir(path.dirname(outPath), { recursive: true });\n await fs.writeFile(outPath, content, 'utf8');\n console.log(\n `Wrote ${outPath} (${content.length} bytes, ${model.length} objects, format=${fmt}).`,\n );\n });\n return cmd;\n}\n\nfunction resolveErdFormat(outPath: string, explicit?: string): 'mermaid' | 'html3d' {\n if (explicit) {\n const e = explicit.toLowerCase();\n if (e === 'mermaid' || e === 'md') return 'mermaid';\n if (e === 'html3d' || e === '3d' || e === 'html') return 'html3d';\n throw new Error(`Unknown --format \"${explicit}\". Expected: mermaid | html3d.`);\n }\n const ext = outPath.toLowerCase();\n if (ext.endsWith('.html') || ext.endsWith('.htm')) return 'html3d';\n return 'mermaid';\n}\n\nasync function loadModel(sourcePath: string): Promise<DatabricksObject[]> {\n if (sourcePath.endsWith('.ddtpac')) {\n const pacContents = await pac.readPac(sourcePath);\n return pacContents.model;\n }\n const loaded = await loadProject(sourcePath);\n const parsed = await parseProjectModel(loaded);\n return parsed as DatabricksObject[];\n}\n","import { Command } from 'commander';\nimport { pac, type DatabricksObject } from '@ddt-tools/core';\n\n/**\n * `ddt verify <pac>` — recompute checksums and confirm the .ddtpac is\n * intact. Catches tampering / corruption / partial-extraction\n * accidents. Sets up the Enterprise-tier signing chain — a signed pac\n * is `verify`+`signature-check` together.\n */\nexport function verifyCommand(): Command {\n const cmd = new Command('verify');\n cmd\n .description('Recompute checksums on a .ddtpac and confirm every object matches the manifest.')\n .requiredOption('--pac <path>', 'Path to the .ddtpac to verify.')\n .option('--json', 'Emit JSON instead of human-readable output.', false)\n .action(async (opts) => {\n const contents = await pac.readPac(String(opts.pac));\n const expected = contents.checksums;\n const actual = pac.computeChecksums(contents.model);\n\n const missing: string[] = [];\n const mismatched: Array<{ id: string; expected: string; actual: string }> = [];\n const orphaned: string[] = [];\n\n const expectedIds = new Set(Object.keys(expected));\n const actualIds = new Set(Object.keys(actual));\n for (const id of expectedIds) {\n if (!actualIds.has(id)) {\n missing.push(id);\n continue;\n }\n if (expected[id] !== actual[id]) {\n mismatched.push({ id, expected: expected[id]!, actual: actual[id]! });\n }\n }\n for (const id of actualIds) {\n if (!expectedIds.has(id)) orphaned.push(id);\n }\n\n const ok = missing.length === 0 && mismatched.length === 0 && orphaned.length === 0;\n if (opts.json) {\n console.log(\n JSON.stringify(\n { ok, missing, mismatched, orphaned, objectCount: contents.model.length },\n null,\n 2,\n ),\n );\n } else {\n console.log(`Pac: ${opts.pac}`);\n console.log(\n `Project: ${contents.manifest.projectName} v${contents.manifest.projectVersion}`,\n );\n console.log(\n `Built: ${contents.manifest.builtAt} by ${contents.manifest.builtBy.name} ${contents.manifest.builtBy.version}`,\n );\n console.log(`Objects: ${contents.model.length}`);\n console.log('');\n if (ok) {\n console.log('✓ verify OK — every checksum matches.');\n } else {\n console.log('✗ verify FAILED');\n if (missing.length > 0) {\n console.log(` missing checksums (${missing.length}):`);\n for (const id of missing) console.log(` ${id}`);\n }\n if (mismatched.length > 0) {\n console.log(` mismatched (${mismatched.length}):`);\n for (const m of mismatched)\n console.log(\n ` ${m.id} expected=${m.expected.slice(0, 12)}… actual=${m.actual.slice(0, 12)}…`,\n );\n }\n if (orphaned.length > 0) {\n console.log(` orphaned (in model but not in checksums) (${orphaned.length}):`);\n for (const id of orphaned) console.log(` ${id}`);\n }\n }\n }\n if (!ok) process.exitCode = 1;\n });\n return cmd;\n}\n\n// Silence unused-import warning when DatabricksObject is only referenced via pac.readPac\nvoid (undefined as unknown as DatabricksObject);\n","import { promises as fs } from 'node:fs';\nimport { Command } from 'commander';\nimport {\n DatabricksExecutor,\n createConnection,\n getProfile,\n revertStepsFromManifest,\n type DeployManifest,\n} from '@ddt-tools/core';\n\n/**\n * `ddt revert --manifest <path>` — undo a previous deploy by executing\n * each step's `reverseSql` in reverse order. Manifests come from\n * `ddt publish --manifest <path>` (the JSON deploy manifest captured\n * after `--apply`).\n *\n * Steps without `reverseSql` are inherently irreversible (DROP, etc.)\n * and skipped with a clear warning. The command exits non-zero if any\n * reverse fails or if any step was irreversible (the user must inspect\n * by hand).\n *\n * Sqitch-equivalent revert flow. Use case: a deploy succeeded but\n * something downstream broke; revert it. Use case: drift is detected\n * and you need to roll back to the last-known-good state.\n *\n * The manifest shape (`DeployManifest`) lives in `@ddt-tools/core` so the\n * `publish` writer, this reader, and `replay` share one contract.\n */\nexport function revertCommand(): Command {\n const cmd = new Command('revert');\n cmd\n .description(\n 'Replay a previous deploy manifest in reverse, executing reverseSql for each successful step.',\n )\n .requiredOption(\n '--manifest <path>',\n 'Path to a JSON deploy manifest from `ddt publish --apply --manifest`.',\n )\n .requiredOption(\n '--connection <name>',\n 'Connection profile to revert against. Should match the original deploy.',\n )\n .requiredOption('--yes', 'Explicit confirmation. Required because revert is destructive.')\n .option(\n '--continue-on-error',\n 'Continue past failed reverse statements. Default: stop on first failure.',\n false,\n )\n .option('--dry-run', 'Print what would be reverted without executing.', false)\n .action(async (opts) => {\n const raw = await fs.readFile(String(opts.manifest), 'utf8');\n const manifest = JSON.parse(raw) as DeployManifest;\n if (manifest.version !== 1) {\n throw new Error(\n `Unsupported manifest version: ${manifest.version}. This CLI understands v1.`,\n );\n }\n\n const profile = await getProfile(String(opts.connection));\n if (profile.auth.host !== manifest.workspaceHost) {\n console.error('');\n console.error(\n `WARNING: manifest's workspaceHost (${manifest.workspaceHost}) doesn't match the profile's host (${profile.auth.host}).`,\n );\n console.error(\n 'Reverting against a different workspace than the original deploy may have unintended effects.',\n );\n console.error('Re-run with the correct --connection, or proceed carefully.');\n console.error('');\n }\n\n // Reverse-iterate; only successful steps need undoing.\n const reverseSteps = revertStepsFromManifest(manifest);\n\n console.log(`Reverting ${reverseSteps.length} step(s) from ${opts.manifest}`);\n console.log(`Original deploy: ${manifest.deployedAt} → ${manifest.workspaceHost}`);\n console.log('');\n\n if (opts.dryRun) {\n for (const s of reverseSteps) {\n const tag = s.reverseSql ? '↩' : '⚠';\n console.log(`${tag} ${s.objectType} ${s.fqn}`);\n if (s.reverseSql) {\n console.log(` ${s.reverseSql.split('\\n')[0]?.slice(0, 100) ?? ''}`);\n } else {\n console.log(` (no reverseSql — IRREVERSIBLE; would be skipped)`);\n }\n }\n const skippable = reverseSteps.filter((s) => !s.reverseSql).length;\n console.log('');\n console.log(\n `Dry-run summary: ${reverseSteps.length - skippable} reversible, ${skippable} irreversible.`,\n );\n return;\n }\n\n const conn = createConnection(profile);\n let succeeded = 0;\n let failed = 0;\n let irreversible = 0;\n try {\n await conn.connect();\n const executor = new DatabricksExecutor(conn);\n for (const s of reverseSteps) {\n if (!s.reverseSql) {\n console.log(`⚠ skip ${s.objectType} ${s.fqn} — irreversible (no reverseSql captured)`);\n irreversible++;\n continue;\n }\n process.stdout.write(`↩ ${s.objectType} ${s.fqn} …`);\n const t0 = Date.now();\n try {\n await executor.execute(s.reverseSql);\n console.log(` ✓ (${Date.now() - t0}ms)`);\n succeeded++;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.log(` ✗ ${msg}`);\n failed++;\n if (!opts.continueOnError) {\n console.error('');\n console.error('Stopping on first failure. Use --continue-on-error to push through.');\n break;\n }\n }\n }\n } finally {\n await conn.disconnect();\n }\n\n console.log('');\n console.log(\n `Summary: ${succeeded} reverted, ${failed} failed, ${irreversible} irreversible.`,\n );\n if (failed > 0 || irreversible > 0) process.exitCode = 1;\n });\n return cmd;\n}\n","/**\n * `ddt snapshot` — surface the TRUST.1 pre-deploy snapshot registry from\n * the CLI.\n *\n * ddt snapshot list [--root <path>] [--json] [--expired-only]\n * ddt snapshot show <batch-id> [--root <path>] [--json]\n * ddt snapshot prune [--root <path>] [--connection <profile>]\n * [--apply] [--yes] [--out <path>]\n *\n * `publish --apply` writes a registry entry under `.ddt/snapshots/<batchId>.json`\n * every time it takes a Delta SHALLOW CLONE pre-deploy. The TTL is per-batch\n * (default 168h). This command lets an operator inspect batches, audit them,\n * and drop both the snapshot tables and the registry rows when the retention\n * horizon has passed.\n *\n * Mirrors `Snowflake/packages/cli/src/commands/snapshot.ts`.\n */\nimport path from 'node:path';\nimport { promises as fs } from 'node:fs';\nimport { Command } from 'commander';\nimport { createConnection, getProfile, queryExecution, safety } from '@ddt-tools/core';\n\nconst DEFAULT_ROOT = safety.DEFAULT_SNAPSHOT_REGISTRY_DIR;\n\nexport function snapshotCommand(): Command {\n const cmd = new Command('snapshot');\n cmd.description(\n 'Inspect / prune the pre-deploy snapshot registry written by `ddt publish --apply`.',\n );\n\n cmd\n .command('list')\n .description('List recorded snapshot batches (newest first).')\n .option('--root <path>', 'Snapshot registry directory.', DEFAULT_ROOT)\n .option('--expired-only', 'Only show batches whose TTL has elapsed.', false)\n .option('--json', 'Emit JSON.', false)\n .action(async (opts: Record<string, unknown>) => {\n const root = String(opts.root);\n const batches = await safety.loadSnapshotRegistry(root);\n const filtered = opts.expiredOnly ? safety.listExpiredBatches(batches) : batches;\n\n if (opts.json) {\n console.log(JSON.stringify(filtered, null, 2));\n return;\n }\n if (filtered.length === 0) {\n console.log(\n opts.expiredOnly\n ? `No expired snapshot batches in ${root}.`\n : `No snapshot batches recorded in ${root}.`,\n );\n return;\n }\n const now = Date.now();\n console.log(\n `${filtered.length} snapshot batch(es) in ${root}` +\n (opts.expiredOnly ? ' (expired only)' : ''),\n );\n for (const b of filtered) {\n const expired = Date.parse(b.expiresAt) <= now ? ' EXPIRED' : '';\n console.log(\n ` ${b.batchId} (${b.entries.length} obj${b.entries.length === 1 ? '' : 's'}) ` +\n `created=${b.createdAt} expires=${b.expiresAt}${expired}`,\n );\n }\n });\n\n cmd\n .command('show')\n .description('Show one batch in full (entries + context).')\n .argument('<batch-id>')\n .option('--root <path>', 'Snapshot registry directory.', DEFAULT_ROOT)\n .option('--json', 'Emit JSON.', false)\n .action(async (batchId: string, opts: Record<string, unknown>) => {\n const root = String(opts.root);\n let batch;\n try {\n batch = await safety.readSnapshotBatch(root, batchId);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error(`Snapshot batch \"${batchId}\" not found in ${root}: ${msg}`);\n process.exitCode = 1;\n return;\n }\n if (opts.json) {\n console.log(JSON.stringify(batch, null, 2));\n return;\n }\n console.log(`Batch: ${batch.batchId}`);\n console.log(`createdAt: ${batch.createdAt}`);\n console.log(`expiresAt: ${batch.expiresAt}`);\n console.log(`ttlHours: ${batch.ttlHours}`);\n if (batch.context) {\n const ctx = batch.context;\n const bits = [\n ctx.projectName ? `project=${ctx.projectName}` : '',\n ctx.projectVersion ? `version=${ctx.projectVersion}` : '',\n ctx.profile ? `profile=${ctx.profile}` : '',\n ctx.pacPath ? `pac=${ctx.pacPath}` : '',\n ].filter(Boolean);\n if (bits.length > 0) console.log(`context: ${bits.join('; ')}`);\n }\n console.log(`Entries (${batch.entries.length}):`);\n for (const e of batch.entries) {\n console.log(\n ` ${e.objectType.padEnd(18)} ${e.sourceFqn} → ${e.snapshotFqn}` +\n (e.triggerCodes.length > 0 ? ` [${e.triggerCodes.join(', ')}]` : ''),\n );\n }\n });\n\n cmd\n .command('prune')\n .description(\n 'Drop snapshots whose TTL has elapsed. Dry-run by default; pass --apply --yes to execute.',\n )\n .option('--root <path>', 'Snapshot registry directory.', DEFAULT_ROOT)\n .option(\n '--connection <profile>',\n 'Connection profile. Required with --apply (the executor needs a live target).',\n )\n .option('--apply', 'Execute DROP statements against --connection. Requires --yes.', false)\n .option('--yes', 'Confirm destructive prune. Required with --apply.', false)\n .option('--out <path>', 'Write the prune SQL (all expired batches concatenated) to this file.')\n .option(\n '--registry-only',\n 'Only remove registry JSON entries (do not emit/execute DROP SQL). ' +\n 'Use when the snapshot tables have already been cleaned up out-of-band.',\n false,\n )\n .action(async (opts: Record<string, unknown>) => {\n const root = String(opts.root);\n const batches = await safety.loadSnapshotRegistry(root);\n const expired = safety.listExpiredBatches(batches);\n\n if (expired.length === 0) {\n console.log(`No expired snapshot batches in ${root}.`);\n return;\n }\n\n const allSql: string[] = [];\n for (const b of expired) {\n allSql.push(...safety.emitPruneSnapshotSql(b));\n }\n const fullSql = allSql.join('\\n');\n\n if (opts.out) {\n const out = path.resolve(String(opts.out));\n await fs.mkdir(path.dirname(out), { recursive: true });\n await fs.writeFile(out, fullSql + '\\n', 'utf8');\n console.log(`Wrote prune SQL → ${out}`);\n }\n\n if (!opts.apply) {\n console.log(\n `${expired.length} expired snapshot batch(es) would be pruned ` +\n `(${countEntries(expired)} object(s) total). ` +\n (opts.registryOnly\n ? 'Pass --apply --yes to remove registry entries.'\n : 'Pass --apply --yes --connection <profile> to execute and remove registry entries.'),\n );\n for (const b of expired) {\n console.log(` ${b.batchId} (expired ${b.expiresAt}, ${b.entries.length} obj)`);\n }\n if (!opts.out) {\n console.log('');\n console.log('--- PRUNE SQL ---');\n console.log(fullSql);\n }\n return;\n }\n\n if (!opts.yes) {\n console.error('--apply requires --yes (destructive prune).');\n process.exitCode = 1;\n return;\n }\n\n let executed = 0;\n let failed = 0;\n if (!opts.registryOnly) {\n if (!opts.connection) {\n console.error('--apply requires --connection <profile> (or pass --registry-only).');\n process.exitCode = 1;\n return;\n }\n const profile = await getProfile(String(opts.connection));\n const conn = createConnection(profile);\n try {\n await conn.connect();\n for (const b of expired) {\n for (const stmt of queryExecution\n .splitStatements(safety.emitPruneSnapshotSql(b).join('\\n'))\n .map((s) => s.sql)) {\n try {\n await conn.executeRows(stmt);\n executed += 1;\n } catch (err) {\n failed += 1;\n const msg = err instanceof Error ? err.message : String(err);\n console.error(` [prune ${b.batchId}] ${msg}\\n ${stmt}`);\n }\n }\n }\n } finally {\n await conn.disconnect();\n }\n }\n\n // Always remove the registry entries we processed (even if some DROPs\n // failed — a partially-dropped batch is now in an unknown state, but\n // keeping its registry row pointing at vanished tables only adds noise\n // to the next prune. Failures were logged above for the operator).\n let removed = 0;\n for (const b of expired) {\n await safety.deleteSnapshotBatch(root, b.batchId);\n removed += 1;\n }\n\n console.log(\n `Pruned ${removed} registry entry/entries` +\n (opts.registryOnly\n ? ' (registry-only, no SQL executed).'\n : ` · ${executed} DROP statement(s) executed` +\n (failed > 0 ? `, ${failed} failed.` : '.')),\n );\n if (failed > 0) process.exitCode = 1;\n });\n\n return cmd;\n}\n\nfunction countEntries(batches: readonly safety.SnapshotBatch[]): number {\n let n = 0;\n for (const b of batches) n += b.entries.length;\n return n;\n}\n","/**\n * `--explain` flag helper — shared across every command that produces a\n * structured report (compare, diagnose, review, impact, cost-estimate,\n * lineage, lint, pr-comment, test, …).\n *\n * Each consumer calls `attachExplainFlag(cmd, { feature, systemPrompt })`\n * during command construction, then awaits `runExplain(buildPrompt, opts)`\n * after the structured output has been printed. The helper:\n *\n * - declares the `--explain` (alias `--ai-explain`) flag,\n * - reads the configured AI provider via `@ddt-tools/core/ai`,\n * - calls `complete()` with a stable system prompt + the consumer's\n * prompt body,\n * - prints the narration to stdout under an \"AI explanation:\" header,\n * - gracefully degrades when no provider is configured (a friendly\n * hint pointing at `ddt ai status` is printed; non-zero exit code is\n * NOT set — `--explain` is best-effort decoration on top of the\n * structured output).\n *\n * Mirrors `Snowflake/packages/cli/src/util/ai-explain.ts`.\n */\nimport type { Command } from 'commander';\nimport { ai } from '@ddt-tools/core';\n\nexport interface ExplainContext {\n feature: string;\n systemPrompt?: string;\n}\n\nconst DEFAULT_SYSTEM_PROMPT = `You are a senior Databricks data engineer reviewing structured output from the DDT CLI. Narrate it for a teammate who has not seen the underlying SQL. Be concrete and specific — reference identifiers by name. Group related items together. Skip information that is already obvious from the structured output; add the missing intent, risks, and follow-up actions. 4-10 sentences total unless the data warrants more.`;\n\nexport function attachExplainFlag(cmd: Command, description?: string): Command {\n const hasExplain = cmd.options.some((o) => o.long === '--explain' || o.long === '--ai-explain');\n if (hasExplain) return cmd;\n cmd.option(\n '--explain',\n description ??\n 'After the structured output, call the configured AI provider to narrate the result in plain English. Requires `ddt ai` to be configured.',\n false,\n );\n return cmd;\n}\n\nexport async function runExplain(\n ctx: ExplainContext,\n opts: { explain?: boolean },\n buildPrompt: () => string,\n): Promise<void> {\n if (!opts.explain) return;\n const system = ctx.systemPrompt ?? DEFAULT_SYSTEM_PROMPT;\n console.log('');\n console.log('AI explanation:');\n try {\n const reply = await ai.complete(\n [\n { role: 'system', content: system },\n { role: 'user', content: buildPrompt() },\n ],\n { feature: ctx.feature },\n );\n for (const line of reply.text.split('\\n')) console.log(' ' + line);\n } catch (err) {\n console.error(' --explain failed: ' + (err instanceof Error ? err.message : String(err)));\n console.error(\n ' Run `ddt ai status` to verify your AI provider is configured (`ddt ai test` to send a probe).',\n );\n }\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport {\n buildDependencyGraph,\n diffDependencyGraphs,\n loadProject,\n pac,\n parseProjectModel,\n renderGraphDot,\n renderGraphMermaid,\n type DatabricksObject,\n type DependencyGraph,\n type DependencyGraphDiff,\n} from '@ddt-tools/core';\nimport { attachExplainFlag, runExplain } from '../util/ai-explain.js';\n\n/**\n * `ddt graph` — emit an object-dependency DAG (Mermaid or DOT) from a\n * `.ddtproj` or `.ddtpac`. Lets reviewers see blast radius before a\n * drop. Inspired by DBeaver's \"Object References\" panel — but at the\n * cross-object level rather than column level.\n *\n * With `--compare-to <other-source>`, diffs the two graphs and (when\n * `--explain` is on) narrates the DAG changes in plain English — the\n * AI Phase 6 \"lineage explanation\" surface.\n */\nexport function graphCommand(): Command {\n const cmd = new Command('graph');\n cmd\n .description('Build an object-dependency DAG and emit it as Mermaid or DOT.')\n .requiredOption('--source <path>', '.ddtproj or .ddtpac to analyze.')\n .option('-o, --out <path>', 'Output file path. Defaults to stdout.')\n .option(\n '--format <fmt>',\n 'mermaid | dot | md (Mermaid wrapped in a markdown fenced block)',\n 'mermaid',\n )\n .option('--json', 'Emit the raw { nodes, edges } JSON instead of a renderer.', false)\n .option(\n '--compare-to <path>',\n 'A second .ddtproj or .ddtpac. When set, emit added / removed / changed nodes + edges (the DAG delta) instead of the static graph.',\n )\n .action(async (opts) => {\n const model = await loadModel(String(opts.source));\n const graph = buildDependencyGraph(model);\n\n let diff: DependencyGraphDiff | undefined;\n if (opts.compareTo) {\n const otherModel = await loadModel(String(opts.compareTo));\n const otherGraph = buildDependencyGraph(otherModel);\n diff = diffDependencyGraphs(otherGraph, graph);\n }\n\n const fmt = String(opts.format ?? 'mermaid').toLowerCase();\n let payload: string;\n if (opts.json) {\n payload = JSON.stringify(diff ?? graph, null, 2);\n } else if (diff) {\n payload = renderDiffMarkdown(diff);\n } else if (fmt === 'mermaid') {\n payload = renderGraphMermaid(graph);\n } else if (fmt === 'dot') {\n payload = renderGraphDot(graph);\n } else if (fmt === 'md') {\n payload = `# Schema dependency graph\\n\\n${graph.nodes.length} node(s), ${graph.edges.length} edge(s).\\n\\n\\`\\`\\`mermaid\\n${renderGraphMermaid(graph)}\\n\\`\\`\\`\\n`;\n } else {\n throw new Error(`Unknown --format: ${fmt}. Use mermaid | dot | md.`);\n }\n\n if (opts.out) {\n const out = path.resolve(String(opts.out));\n await fs.mkdir(path.dirname(out), { recursive: true });\n await fs.writeFile(out, payload + (payload.endsWith('\\n') ? '' : '\\n'), 'utf8');\n console.error(\n `Wrote ${out} (${payload.length} bytes, ${graph.nodes.length} nodes, ${graph.edges.length} edges).`,\n );\n } else {\n process.stdout.write(payload + (payload.endsWith('\\n') ? '' : '\\n'));\n }\n\n await runExplain(\n {\n feature: 'graph.explain',\n systemPrompt: diff\n ? 'You are a data-platform architect narrating a dependency-graph DELTA between two snapshots. Walk through added / removed / changed nodes and edges in plain English. Call out structural shifts (new sources, dropped consumers, type changes) and likely-but-not-yet-broken downstream consequences.'\n : 'You are a data-platform architect explaining a dependency graph. Describe the dominant data-flow shape, point out hot or fragile nodes, and recommend any decomposition the graph suggests.',\n },\n opts as { explain?: boolean },\n () => (diff ? buildDiffPrompt(diff) : buildGraphPrompt(graph)),\n );\n });\n attachExplainFlag(cmd);\n return cmd;\n}\n\nfunction renderDiffMarkdown(d: DependencyGraphDiff): string {\n const lines: string[] = ['# Dependency-graph delta', ''];\n lines.push(\n `**Summary**: ${d.summary.nodeDelta >= 0 ? '+' : ''}${d.summary.nodeDelta} nodes, ` +\n `${d.summary.edgeDelta >= 0 ? '+' : ''}${d.summary.edgeDelta} edges. ` +\n `${d.addedNodes.length} added node(s), ${d.removedNodes.length} removed node(s), ` +\n `${d.changedNodes.length} changed node(s).`,\n );\n lines.push('');\n if (d.addedNodes.length > 0) {\n lines.push('## Added nodes');\n for (const n of d.addedNodes) lines.push(`- \\`${n.fqn}\\` (${n.objectType})`);\n lines.push('');\n }\n if (d.removedNodes.length > 0) {\n lines.push('## Removed nodes');\n for (const n of d.removedNodes) lines.push(`- \\`${n.fqn}\\` (${n.objectType})`);\n lines.push('');\n }\n if (d.changedNodes.length > 0) {\n lines.push('## Changed nodes (objectType)');\n for (const c of d.changedNodes) lines.push(`- \\`${c.fqn}\\`: ${c.before} → ${c.after}`);\n lines.push('');\n }\n if (d.addedEdges.length > 0) {\n lines.push('## Added edges');\n for (const e of d.addedEdges) lines.push(`- \\`${e.from}\\` → \\`${e.to}\\` (${e.kind})`);\n lines.push('');\n }\n if (d.removedEdges.length > 0) {\n lines.push('## Removed edges');\n for (const e of d.removedEdges) lines.push(`- \\`${e.from}\\` → \\`${e.to}\\` (${e.kind})`);\n }\n return lines.join('\\n');\n}\n\nfunction buildGraphPrompt(g: DependencyGraph): string {\n const sample = g.edges.slice(0, 40).map((e) => ` - ${e.from} -> ${e.to}`);\n return [\n `Dependency graph: ${g.nodes.length} nodes, ${g.edges.length} edges.`,\n '',\n 'Edges (up to 40):',\n ...sample,\n '',\n 'Narrate this graph in plain English.',\n ].join('\\n');\n}\n\nfunction buildDiffPrompt(d: DependencyGraphDiff): string {\n const lines: string[] = [];\n lines.push(\n `Graph delta: ${d.summary.nodeDelta >= 0 ? '+' : ''}${d.summary.nodeDelta} nodes, ` +\n `${d.summary.edgeDelta >= 0 ? '+' : ''}${d.summary.edgeDelta} edges.`,\n );\n if (d.addedNodes.length > 0) {\n lines.push('', `Added nodes (${d.addedNodes.length}, up to 20):`);\n for (const n of d.addedNodes.slice(0, 20)) lines.push(` + ${n.fqn} (${n.objectType})`);\n }\n if (d.removedNodes.length > 0) {\n lines.push('', `Removed nodes (${d.removedNodes.length}, up to 20):`);\n for (const n of d.removedNodes.slice(0, 20)) lines.push(` - ${n.fqn} (${n.objectType})`);\n }\n if (d.changedNodes.length > 0) {\n lines.push('', `Changed nodes (${d.changedNodes.length}):`);\n for (const c of d.changedNodes.slice(0, 20))\n lines.push(` ~ ${c.fqn}: ${c.before} -> ${c.after}`);\n }\n if (d.addedEdges.length > 0) {\n lines.push('', `Added edges (${d.addedEdges.length}, up to 20):`);\n for (const e of d.addedEdges.slice(0, 20)) lines.push(` + ${e.from} -> ${e.to}`);\n }\n if (d.removedEdges.length > 0) {\n lines.push('', `Removed edges (${d.removedEdges.length}, up to 20):`);\n for (const e of d.removedEdges.slice(0, 20)) lines.push(` - ${e.from} -> ${e.to}`);\n }\n lines.push(\n '',\n 'Narrate this delta in plain English. Highlight structural shifts and likely downstream consequences.',\n );\n return lines.join('\\n');\n}\n\nasync function loadModel(sourcePath: string): Promise<DatabricksObject[]> {\n if (sourcePath.endsWith('.ddtpac')) {\n const c = await pac.readPac(sourcePath);\n return c.model;\n }\n const loaded = await loadProject(sourcePath);\n return (await parseProjectModel(loaded)) as DatabricksObject[];\n}\n","import { promises as fs } from 'node:fs';\nimport { randomUUID } from 'node:crypto';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport {\n loadProject,\n pac,\n parseProjectModel,\n lineage,\n columnLineage,\n type DatabricksObject,\n} from '@ddt-tools/core';\nimport { attachExplainFlag, runExplain } from '../util/ai-explain.js';\n\n/**\n * CLL.7-followup runtime: thread CLI flags + `.ddt/lineage.json` config\n * through the OpenLineage substrate. Exported so vitest can drive it\n * directly with a stub fetchImpl + readFile (no real network / disk).\n */\nexport interface EmitOpenLineageCliInputs {\n dag: columnLineage.ColumnLineageDag;\n endpointFlag?: string;\n configPath?: string;\n namespace?: string;\n jobNamespace?: string;\n job?: string;\n /**\n * OpenLineage emit mode. `auto` resolves to `per-event` when the\n * built events array has ≤ AUTO_MODE_THRESHOLD entries, `batch`\n * otherwise. Resolution happens at the CLI layer; the substrate\n * only ever sees the concrete `per-event` or `batch`.\n */\n mode?: 'per-event' | 'batch' | 'auto';\n /** OpenLineage event type (subset of the spec enum). Default `COMPLETE`. */\n eventType?: 'START' | 'RUNNING' | 'COMPLETE' | 'ABORT' | 'FAIL' | 'OTHER';\n /**\n * Override the event timestamp (ISO 8601). Default: now() at emit time.\n * Useful for backfill — historical pipeline runs replayed into Marquez/\n * OpenMetadata keep their original eventTime instead of being collapsed\n * onto \"now\".\n */\n eventTime?: string;\n /** Per-request timeout in ms (positive integer; 0/negative/NaN are ignored). */\n timeoutMs?: number;\n token?: string;\n /** Override OpenLineage producer URL identifying the emitting tool. */\n producer?: string;\n /** Repeatable `name=value` strings from `--emit-openlineage-header`. */\n headerArgs?: readonly string[];\n runId?: string;\n dryRun?: boolean;\n /** Persist built events JSON to this path on disk (audit / replay). */\n eventsOutPath?: string;\n /**\n * Output format for the events-out file. `json` (default) writes the\n * familiar `{events: [...]}` wrapper with pretty-printed indentation;\n * `jsonl` writes one event per line (newline-delimited JSON) for\n * streaming-ingest pipelines (Vector / Fluent Bit / OpenTelemetry\n * collectors / Databricks Auto Loader).\n */\n eventsOutFormat?: 'json' | 'jsonl';\n /** Skip the POST when the events array is empty (no DAG produced 0 events). */\n skipEmpty?: boolean;\n /**\n * Refuse to emit when the built events count is below this threshold.\n * Returns `ok: false` with `MIN_EVENTS_NOT_MET`. CI-friendly guard\n * against silent lineage gaps — a refactor that accidentally bypasses\n * column-lineage extraction would otherwise quietly emit zero events\n * and pass the build.\n */\n minEvents?: number;\n sourceHint?: string;\n}\n\nconst VALID_OL_EVENT_TYPES = new Set<EmitOpenLineageCliInputs['eventType']>([\n 'START',\n 'RUNNING',\n 'COMPLETE',\n 'ABORT',\n 'FAIL',\n 'OTHER',\n]);\n\n/**\n * Validate `--emit-openlineage-event-type <value>` against the OL enum.\n * Returns the upper-cased value when valid. Throws with operator-facing\n * message when unknown — the action handler surfaces the throw as exit\n * code 1 (uncaught throw from commander action) which is the same\n * convention used by other input-validation throws in this CLI.\n */\nexport function validateEventType(raw: string): EmitOpenLineageCliInputs['eventType'] {\n const upper = raw.toUpperCase() as EmitOpenLineageCliInputs['eventType'];\n if (!VALID_OL_EVENT_TYPES.has(upper)) {\n throw new Error(\n `--emit-openlineage-event-type ${JSON.stringify(raw)} is not a valid OpenLineage event type. ` +\n `Use one of: ${[...VALID_OL_EVENT_TYPES].join(', ')}.`,\n );\n }\n return upper;\n}\n\n/**\n * Threshold at which `--emit-openlineage-mode auto` flips from\n * `per-event` (one HTTP POST per event, easier to debug in the\n * collector UI) to `batch` (single POST with `{events: [...]}`,\n * amortizes HTTP overhead). Operators with non-default cost or\n * latency requirements can still force the mode explicitly.\n */\nexport const AUTO_MODE_THRESHOLD = 10;\n\n/**\n * Resolve `mode: 'auto'` based on the built events count. Returns the\n * concrete `per-event` / `batch` value; pass-through for non-auto.\n */\nexport function resolveAutoMode(\n mode: 'per-event' | 'batch' | 'auto',\n eventCount: number,\n): 'per-event' | 'batch' {\n if (mode !== 'auto') return mode;\n return eventCount <= AUTO_MODE_THRESHOLD ? 'per-event' : 'batch';\n}\n\n/**\n * Validate `--emit-openlineage-mode <value>` against per-event / batch / auto.\n * Returns the lower-cased value when valid. Throws with operator-facing\n * message on unknown.\n */\nexport function validateMode(raw: string): 'per-event' | 'batch' | 'auto' {\n const lower = raw.toLowerCase();\n if (lower !== 'per-event' && lower !== 'batch' && lower !== 'auto') {\n throw new Error(\n `--emit-openlineage-mode ${JSON.stringify(raw)} is not valid. ` +\n `Use one of: per-event, batch, auto.`,\n );\n }\n return lower as 'per-event' | 'batch' | 'auto';\n}\n\n/**\n * Validate `--emit-openlineage-events-out-format <fmt>` value. Returns\n * the lower-cased value when valid (`json` or `jsonl`). Throws with\n * operator-facing message when unknown.\n */\nexport function validateEventsOutFormat(raw: string): 'json' | 'jsonl' {\n const lower = raw.toLowerCase();\n if (lower !== 'json' && lower !== 'jsonl') {\n throw new Error(\n `--emit-openlineage-events-out-format ${JSON.stringify(raw)} is not valid. ` +\n `Use one of: json, jsonl.`,\n );\n }\n return lower;\n}\n\n/**\n * Validate `--emit-openlineage-event-time <iso>` as a parseable timestamp.\n * Returns the canonical ISO 8601 form (`new Date(raw).toISOString()`) so\n * the value emitted in every OL event is normalized regardless of input\n * shape (`2026-05-18T20:00:00Z` and `2026-05-18T16:00:00-04:00` both\n * normalize to the same UTC instant). Throws with operator-facing\n * message on invalid input.\n */\nexport function validateEventTime(raw: string): string {\n const parsed = new Date(raw);\n if (Number.isNaN(parsed.getTime())) {\n throw new Error(\n `--emit-openlineage-event-time ${JSON.stringify(raw)} is not a valid ISO 8601 timestamp. ` +\n `Examples: 2026-05-18T20:00:00Z, 2026-05-18T16:00:00-04:00.`,\n );\n }\n return parsed.toISOString();\n}\n\n/**\n * Parse `--emit-openlineage-header name=value` repeatable strings into\n * an `{name: value}` record. Splits on the first `=` only so values\n * containing `=` (e.g. base64-encoded tokens) survive. Strings missing\n * `=` or with empty name are skipped with a stderr note.\n */\nexport function parseHeaderArgs(\n args: readonly string[] | undefined,\n stderr: (chunk: string) => void = () => {},\n): Record<string, string> {\n const out: Record<string, string> = {};\n if (!args || args.length === 0) return out;\n for (const raw of args) {\n const eq = raw.indexOf('=');\n if (eq <= 0) {\n stderr(\n `Ignoring malformed --emit-openlineage-header value ${JSON.stringify(raw)} (expected name=value).\\n`,\n );\n continue;\n }\n const name = raw.slice(0, eq).trim();\n const value = raw.slice(eq + 1);\n if (!name) {\n stderr(`Ignoring --emit-openlineage-header with empty name.\\n`);\n continue;\n }\n out[name] = value;\n }\n return out;\n}\n\nexport interface EmitOpenLineageCliDeps {\n readFile?: (p: string) => Promise<string>;\n writeFile?: (p: string, data: string) => Promise<void>;\n env?: Record<string, string | undefined>;\n fetchImpl?: typeof fetch;\n now?: () => Date;\n uuid?: () => string;\n stdout?: (chunk: string) => void;\n stderr?: (chunk: string) => void;\n}\n\nexport interface EmitOpenLineageCliOutcome {\n ok: boolean;\n events: number;\n succeeded?: number;\n failed?: number;\n error?: { code: string; message: string };\n}\n\nexport async function emitOpenLineageFromCli(\n inputs: EmitOpenLineageCliInputs,\n deps: EmitOpenLineageCliDeps = {},\n): Promise<EmitOpenLineageCliOutcome> {\n const stdout = deps.stdout ?? ((c: string) => process.stdout.write(c));\n const stderr = deps.stderr ?? ((c: string) => process.stderr.write(c));\n const readFile = deps.readFile ?? ((p: string) => fs.readFile(p, 'utf8'));\n const writeFile =\n deps.writeFile ??\n (async (p: string, data: string) => {\n await fs.mkdir(path.dirname(p), { recursive: true });\n await fs.writeFile(p, data, 'utf8');\n });\n const env = deps.env ?? (process.env as Record<string, string | undefined>);\n const now = deps.now ?? (() => new Date());\n const uuid = deps.uuid ?? (() => randomUUID());\n\n let loaded: columnLineage.OpenLineageConfig | undefined;\n const configPath = inputs.configPath ?? columnLineage.DEFAULT_OPENLINEAGE_CONFIG_FILE_REL;\n try {\n const raw = await readFile(configPath);\n const json = JSON.parse(raw);\n const parsed = columnLineage.parseOpenLineageConfig(json);\n if (!parsed.config) {\n const lines = parsed.errors.map((e) => ` - ${e.path}: ${e.message}`);\n stderr(`Failed to parse ${configPath}:\\n${lines.join('\\n')}\\n`);\n return {\n ok: false,\n events: 0,\n error: { code: 'CONFIG_PARSE_FAILED', message: `${configPath} did not validate` },\n };\n }\n loaded = parsed.config;\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code !== 'ENOENT') {\n stderr(`Failed reading ${configPath}: ${(err as Error).message}\\n`);\n return {\n ok: false,\n events: 0,\n error: { code: 'CONFIG_READ_FAILED', message: (err as Error).message },\n };\n }\n // Missing config file is fine when the CLI flag supplies the endpoint.\n }\n\n const overrides: Partial<columnLineage.OpenLineageConfig> = {};\n if (inputs.endpointFlag) overrides.endpoint = inputs.endpointFlag;\n if (inputs.namespace) overrides.datasetNamespace = inputs.namespace;\n if (inputs.jobNamespace) overrides.jobNamespace = inputs.jobNamespace;\n if (inputs.job) overrides.jobName = inputs.job;\n // `auto` is a CLI-layer mode resolved AFTER buildOpenLineageEvents\n // based on events.length. Don't push it to the substrate; the\n // substrate's mode is always per-event or batch.\n if (inputs.mode && inputs.mode !== 'auto') overrides.mode = inputs.mode;\n if (\n typeof inputs.timeoutMs === 'number' &&\n Number.isFinite(inputs.timeoutMs) &&\n inputs.timeoutMs > 0\n ) {\n overrides.timeoutMs = Math.floor(inputs.timeoutMs);\n }\n if (inputs.token) overrides.bearerToken = inputs.token;\n if (inputs.producer && inputs.producer.trim().length > 0)\n overrides.producer = inputs.producer.trim();\n const cliHeaders = parseHeaderArgs(inputs.headerArgs, stderr);\n if (Object.keys(cliHeaders).length > 0) overrides.headers = cliHeaders;\n const merged = columnLineage.mergeOpenLineageCliOverrides(loaded, overrides);\n\n const validated = columnLineage.validateOpenLineageConfig(merged);\n if (!validated.ok) {\n const lines = validated.errors.map((e) => ` - ${e.path}: ${e.message}`);\n stderr(`OpenLineage emit refused:\\n${lines.join('\\n')}\\n`);\n return {\n ok: false,\n events: 0,\n error: { code: 'CONFIG_INCOMPLETE', message: validated.errors[0]!.message },\n };\n }\n\n const resolved = columnLineage.resolveEnvPlaceholders(validated.resolved, env);\n if (!resolved.ok) {\n const lines = resolved.missing.map((m) => ` - ${m.path}: missing env var ${m.envKey}`);\n stderr(`OpenLineage env placeholders unresolved:\\n${lines.join('\\n')}\\n`);\n return {\n ok: false,\n events: 0,\n error: { code: 'ENV_UNRESOLVED', message: resolved.missing[0]!.envKey },\n };\n }\n const final = resolved.resolved;\n\n const jobName = final.jobName ?? inputs.sourceHint ?? 'ddt-lineage';\n const eventType = inputs.eventType ?? 'COMPLETE';\n const events = columnLineage.buildOpenLineageEvents(inputs.dag, {\n runId: inputs.runId ?? uuid(),\n jobName,\n jobNamespace: final.jobNamespace ?? columnLineage.DEFAULT_OPENLINEAGE_JOB_NAMESPACE,\n ...(final.datasetNamespace ? { datasetNamespace: final.datasetNamespace } : {}),\n ...(final.producer ? { producer: final.producer } : {}),\n eventTime: inputs.eventTime ?? now().toISOString(),\n eventType,\n });\n\n if (inputs.eventsOutPath) {\n const format = inputs.eventsOutFormat ?? 'json';\n const payload =\n format === 'jsonl'\n ? events.map((e) => JSON.stringify(e)).join('\\n') + '\\n'\n : JSON.stringify({ events }, null, 2) + '\\n';\n await writeFile(inputs.eventsOutPath, payload);\n stderr(\n `OpenLineage: wrote ${events.length} event(s) to ${inputs.eventsOutPath} (${format}).\\n`,\n );\n }\n\n // CI guard: fail before dry-run / POST when events.length is below\n // the operator-supplied threshold. Catches silent lineage gaps after\n // a refactor that bypasses column-lineage extraction.\n if (\n typeof inputs.minEvents === 'number' &&\n Number.isFinite(inputs.minEvents) &&\n inputs.minEvents > 0 &&\n events.length < inputs.minEvents\n ) {\n stderr(\n `OpenLineage: built ${events.length} event(s), below --emit-openlineage-min-events=${inputs.minEvents}; refusing to emit.\\n`,\n );\n return {\n ok: false,\n events: events.length,\n error: {\n code: 'MIN_EVENTS_NOT_MET',\n message: `built ${events.length} events, expected >= ${inputs.minEvents}`,\n },\n };\n }\n\n if (inputs.dryRun) {\n stdout(JSON.stringify({ events }, null, 2) + '\\n');\n return { ok: true, events: events.length };\n }\n\n if (events.length === 0 && inputs.skipEmpty) {\n stderr(\n 'OpenLineage: 0 events to emit (DAG empty) and --emit-openlineage-skip-empty set; skipping POST.\\n',\n );\n return { ok: true, events: 0, succeeded: 0, failed: 0 };\n }\n\n // Resolve `mode: auto` AFTER buildOpenLineageEvents so the decision\n // sees the actual events count. Substrate's `final.mode` is always\n // per-event / batch — auto only lives at the CLI layer.\n const concreteMode: 'per-event' | 'batch' =\n inputs.mode === 'auto' ? resolveAutoMode('auto', events.length) : (final.mode ?? 'per-event');\n if (inputs.mode === 'auto') {\n stderr(\n `OpenLineage: --emit-openlineage-mode=auto resolved to ${concreteMode} ` +\n `(${events.length} event(s), threshold=${AUTO_MODE_THRESHOLD}).\\n`,\n );\n }\n\n const result = await columnLineage.emitOpenLineageEvents(events, final.endpoint!, {\n ...(final.bearerToken ? { bearerToken: final.bearerToken } : {}),\n ...(final.headers ? { headers: final.headers } : {}),\n mode: concreteMode,\n ...(typeof final.timeoutMs === 'number' ? { timeoutMs: final.timeoutMs } : {}),\n ...(deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {}),\n });\n stderr(\n `OpenLineage: ${result.succeeded}/${result.totalEvents} events delivered to ${final.endpoint} (${result.failed} failed).\\n`,\n );\n return {\n ok: result.failed === 0,\n events: result.totalEvents,\n succeeded: result.succeeded,\n failed: result.failed,\n };\n}\n\n/**\n * `ddt lineage` — extract data-flow lineage from a `.ddtproj` or\n * `.ddtpac` and emit it as Mermaid, DOT, JSON, or Markdown.\n *\n * Distinct from `ddt graph`: graph is FQN-level dependency edges\n * (A references B). Lineage adds direction-of-data-flow classification\n * (READS_FROM vs WRITES_TO), upstream/downstream traversal, and\n * column-level best-effort tagging for view SELECT lists.\n *\n * Mirrors `sdt lineage`.\n */\nexport function lineageCommand(): Command {\n const cmd = new Command('lineage');\n cmd\n .description('Extract data-flow lineage from a .ddtproj, .ddtpac, or dbt manifest.json.')\n .option('--source <path>', '.ddtproj or .ddtpac to analyze.')\n .option(\n '--dbt-manifest <path>',\n 'Extract column-level lineage from a dbt target/manifest.json (or project root).',\n )\n .option(\n '--fqn <name>',\n 'Focus on this fully-qualified name; restrict the graph to its upstream + downstream slice.',\n )\n .option(\n '--direction <kind>',\n 'When --fqn is set, restrict to upstream | downstream | both. Default both.',\n 'both',\n )\n .option('--depth <n>', 'Max traversal depth from --fqn. Default unbounded.', (v) =>\n parseInt(v, 10),\n )\n .option('--format <fmt>', 'mermaid | dot | json | markdown. Default mermaid.', 'mermaid')\n .option('--columns', 'Include best-effort column-level lineage for view SELECT lists.', false)\n .option(\n '--column-dag',\n 'Build a true per-column DAG via the CLL.1/2/3 substrate. Walks every VIEW / MATERIALIZED_VIEW / STREAMING_TABLE body in the project model, extracts column-level lineage, assembles the DAG, and emits Mermaid (default) or JSON. Composes with --fqn (focus to one object) and --out.',\n false,\n )\n .option('--max-edges <n>', 'Truncate large graphs at this edge count.', (v) => parseInt(v, 10))\n .option('-o, --out <path>', 'Output file path. Defaults to stdout.')\n .option(\n '--emit-openlineage [endpoint]',\n 'CLL.7-followup: emit the column DAG as OpenLineage RunEvents to the given collector URL. When the flag is given without a value, the endpoint from .ddt/lineage.json is used. Requires --column-dag (or --dbt-manifest).',\n )\n .option(\n '--emit-openlineage-config <path>',\n 'Override the config-file location (default .ddt/lineage.json).',\n )\n .option(\n '--emit-openlineage-namespace <ns>',\n 'Override the OpenLineage dataset namespace (default databricks).',\n )\n .option(\n '--emit-openlineage-job-namespace <ns>',\n 'Override the OpenLineage job.namespace (default ddt). Groups jobs across deployments in Marquez/OpenMetadata.',\n )\n .option(\n '--emit-openlineage-job <name>',\n 'Override the OpenLineage job.name (default derived from --source).',\n )\n .option(\n '--emit-openlineage-mode <mode>',\n 'OpenLineage emit mode: per-event (default) | batch | auto. `auto` resolves to per-event when the DAG has ≤10 events (easier to debug in Marquez UI) and batch when >10 (amortizes HTTP overhead).',\n )\n .option(\n '--emit-openlineage-timeout-ms <ms>',\n 'Override per-request timeout (positive integer, default 10000ms).',\n (v) => parseInt(v, 10),\n )\n .option(\n '--emit-openlineage-token <token>',\n 'Override bearer token (supports env:VAR_NAME for indirection).',\n )\n .option(\n '--emit-openlineage-header <k=v>',\n 'Extra HTTP header attached to every OpenLineage POST (repeatable). Format: name=value. Values support env:VAR_NAME for indirection.',\n (val: string, prev: string[]) => [...prev, val],\n [] as string[],\n )\n .option(\n '--emit-openlineage-producer <url>',\n 'Override the OpenLineage producer URL (identifies the emitting tool to the collector). Default: https://github.com/GVOrganization/SDT.',\n )\n .option(\n '--emit-openlineage-event-type <type>',\n 'OpenLineage event type: COMPLETE (default), START, RUNNING, ABORT, FAIL, or OTHER. Use START + COMPLETE pairs (sharing --emit-openlineage-run-id) for run-lifecycle modelling.',\n )\n .option(\n '--emit-openlineage-event-time <iso>',\n 'Override the OpenLineage eventTime (ISO 8601). Default: now() at emit time. Use for backfill — replay historical pipeline runs into Marquez/OpenMetadata with their original timestamps instead of \"now\".',\n )\n .option(\n '--emit-openlineage-run-id <id>',\n 'Stable runId (UUID v4). Default: generated per invocation.',\n )\n .option(\n '--emit-openlineage-dry-run',\n 'Build OpenLineage events but do not POST — print the events JSON to stdout instead.',\n false,\n )\n .option(\n '--emit-openlineage-events-out <path>',\n 'Also write the built events JSON to <path> (audit / replay). Independent of --dry-run; combined yields write-only-no-POST.',\n )\n .option(\n '--emit-openlineage-events-out-format <fmt>',\n 'Output format for --emit-openlineage-events-out: json (default, `{events: [...]}` wrapper) or jsonl (newline-delimited, one event per line). Use jsonl for streaming-ingest pipelines (Vector, Fluent Bit, OpenTelemetry collectors, Databricks Auto Loader).',\n )\n .option(\n '--emit-openlineage-skip-empty',\n 'Skip the POST when the built events array is empty (default behavior is to still hit the collector with 0 events in batch mode). Useful in CI when lineage extraction may produce an empty DAG and noisy 0-event traffic is undesirable.',\n false,\n )\n .option(\n '--emit-openlineage-min-events <n>',\n 'CI assertion: refuse to emit (exit 2) when the built events count is below this threshold. Catches silent lineage gaps after a refactor that bypasses column-lineage extraction. Skip-empty composes naturally — set min-events=1 to force every run to produce ≥1 event.',\n (v) => parseInt(v, 10),\n )\n .action(async (opts) => {\n // CLL.7-followup guard (iter 193): refuse --emit-openlineage when\n // neither --column-dag nor --dbt-manifest is in play, because the\n // default FQN-level lineage path doesn't produce a column DAG and\n // the OL columnLineage facet would be empty. Silent-no-op here was\n // a footgun — operators forgetting --column-dag got 0 events.\n if (opts.emitOpenlineage && !opts.columnDag && !opts.dbtManifest) {\n process.stderr.write(\n '--emit-openlineage requires --column-dag (CLL.2 DAG) or --dbt-manifest. ' +\n 'The default FQN-level lineage path has no column-level facet to emit. ' +\n 'Re-run with --column-dag --source <path> or --dbt-manifest <path>.\\n',\n );\n process.exitCode = 2;\n return;\n }\n\n // CLL.4: column-DAG mode — uses CLL.1/2/3 substrate, distinct from\n // the FQN-graph `--columns` hint above.\n if (opts.columnDag) {\n if (!opts.source) throw new Error('--column-dag requires --source <path>.');\n const model = await loadModel(String(opts.source));\n const inputs = collectColumnLineageInputs(model);\n const dag = columnLineage.buildColumnLineageDag(inputs);\n let renderedDag = dag;\n if (opts.fqn) {\n const focus = String(opts.fqn);\n const direction = String(opts.direction ?? 'both').toLowerCase() as\n | 'upstream'\n | 'downstream'\n | 'both';\n renderedDag = columnLineage.sliceColumnDag(dag, focus, direction);\n }\n const fmt = String(opts.format ?? 'mermaid').toLowerCase();\n if (!['mermaid', 'json'].includes(fmt)) {\n throw new Error(`--column-dag only supports --format mermaid|json (got ${fmt}).`);\n }\n const payload =\n fmt === 'json'\n ? JSON.stringify(columnLineage.renderDagJson(renderedDag), null, 2)\n : columnLineage.renderDagMermaid(renderedDag);\n if (opts.out) {\n const out = path.resolve(String(opts.out));\n await fs.mkdir(path.dirname(out), { recursive: true });\n await fs.writeFile(out, payload + '\\n', 'utf8');\n console.error(\n `Wrote ${out} (${renderedDag.nodes.size} nodes, ${renderedDag.edges.length} edges).`,\n );\n } else if (!opts.emitOpenlineage) {\n // Suppress stdout emission when we're piping into the OL --dry-run\n // path so the events JSON is the only thing on stdout.\n process.stdout.write(payload + '\\n');\n }\n if (opts.emitOpenlineage) {\n const endpointFlag =\n typeof opts.emitOpenlineage === 'string' && opts.emitOpenlineage.length > 0\n ? String(opts.emitOpenlineage)\n : undefined;\n const sourceHint = opts.source\n ? path.basename(String(opts.source)).replace(/\\.(ddtproj|ddtpac)$/i, '')\n : undefined;\n const outcome = await emitOpenLineageFromCli({\n dag: renderedDag,\n ...(endpointFlag ? { endpointFlag } : {}),\n ...(opts.emitOpenlineageConfig\n ? { configPath: String(opts.emitOpenlineageConfig) }\n : {}),\n ...(opts.emitOpenlineageNamespace\n ? { namespace: String(opts.emitOpenlineageNamespace) }\n : {}),\n ...(opts.emitOpenlineageJobNamespace\n ? { jobNamespace: String(opts.emitOpenlineageJobNamespace) }\n : {}),\n ...(opts.emitOpenlineageJob ? { job: String(opts.emitOpenlineageJob) } : {}),\n ...(opts.emitOpenlineageMode\n ? { mode: validateMode(String(opts.emitOpenlineageMode)) }\n : {}),\n ...(opts.emitOpenlineageEventType\n ? { eventType: validateEventType(String(opts.emitOpenlineageEventType)) }\n : {}),\n ...(opts.emitOpenlineageEventTime\n ? { eventTime: validateEventTime(String(opts.emitOpenlineageEventTime)) }\n : {}),\n ...(typeof opts.emitOpenlineageTimeoutMs === 'number'\n ? { timeoutMs: opts.emitOpenlineageTimeoutMs }\n : {}),\n ...(opts.emitOpenlineageToken ? { token: String(opts.emitOpenlineageToken) } : {}),\n ...(opts.emitOpenlineageProducer\n ? { producer: String(opts.emitOpenlineageProducer) }\n : {}),\n ...(Array.isArray(opts.emitOpenlineageHeader) && opts.emitOpenlineageHeader.length > 0\n ? { headerArgs: opts.emitOpenlineageHeader as string[] }\n : {}),\n ...(opts.emitOpenlineageRunId ? { runId: String(opts.emitOpenlineageRunId) } : {}),\n ...(opts.emitOpenlineageDryRun ? { dryRun: true } : {}),\n ...(opts.emitOpenlineageEventsOut\n ? { eventsOutPath: String(opts.emitOpenlineageEventsOut) }\n : {}),\n ...(opts.emitOpenlineageEventsOutFormat\n ? {\n eventsOutFormat: validateEventsOutFormat(\n String(opts.emitOpenlineageEventsOutFormat),\n ),\n }\n : {}),\n ...(opts.emitOpenlineageSkipEmpty ? { skipEmpty: true } : {}),\n ...(typeof opts.emitOpenlineageMinEvents === 'number' &&\n opts.emitOpenlineageMinEvents > 0\n ? { minEvents: opts.emitOpenlineageMinEvents }\n : {}),\n ...(sourceHint ? { sourceHint } : {}),\n });\n if (!outcome.ok) {\n process.exitCode = 2;\n }\n }\n return;\n }\n if (opts.dbtManifest) {\n const result = await columnLineage.extractDbtManifestLineage(String(opts.dbtManifest));\n const fmt = String(opts.format ?? 'mermaid').toLowerCase();\n const payload =\n fmt === 'json'\n ? columnLineage.renderDbtLineageJson(result)\n : columnLineage.renderDbtLineageMermaid(result);\n if (result.skipped.length > 0) {\n for (const s of result.skipped) console.error(`Skipped ${s.nodeId}: ${s.reason}`);\n }\n if (opts.out) {\n const out = path.resolve(String(opts.out));\n await fs.mkdir(path.dirname(out), { recursive: true });\n await fs.writeFile(out, payload + '\\n', 'utf8');\n console.error(\n `Wrote ${out} (${result.models.length} models, ${result.skipped.length} skipped).`,\n );\n } else if (!opts.emitOpenlineage) {\n process.stdout.write(payload + '\\n');\n }\n if (opts.emitOpenlineage) {\n const dag = columnLineage.buildColumnLineageDag(\n result.models.map((m) => ({ objectFqn: m.fqn, lineage: m.lineage })),\n );\n const endpointFlag =\n typeof opts.emitOpenlineage === 'string' && opts.emitOpenlineage.length > 0\n ? String(opts.emitOpenlineage)\n : undefined;\n const sourceHint = `dbt:${path.basename(String(opts.dbtManifest)).replace(/\\.json$/i, '')}`;\n const outcome = await emitOpenLineageFromCli({\n dag,\n ...(endpointFlag ? { endpointFlag } : {}),\n ...(opts.emitOpenlineageConfig\n ? { configPath: String(opts.emitOpenlineageConfig) }\n : {}),\n ...(opts.emitOpenlineageNamespace\n ? { namespace: String(opts.emitOpenlineageNamespace) }\n : {}),\n ...(opts.emitOpenlineageJobNamespace\n ? { jobNamespace: String(opts.emitOpenlineageJobNamespace) }\n : {}),\n ...(opts.emitOpenlineageJob ? { job: String(opts.emitOpenlineageJob) } : {}),\n ...(opts.emitOpenlineageMode\n ? { mode: validateMode(String(opts.emitOpenlineageMode)) }\n : {}),\n ...(opts.emitOpenlineageEventType\n ? { eventType: validateEventType(String(opts.emitOpenlineageEventType)) }\n : {}),\n ...(opts.emitOpenlineageEventTime\n ? { eventTime: validateEventTime(String(opts.emitOpenlineageEventTime)) }\n : {}),\n ...(typeof opts.emitOpenlineageTimeoutMs === 'number'\n ? { timeoutMs: opts.emitOpenlineageTimeoutMs }\n : {}),\n ...(opts.emitOpenlineageToken ? { token: String(opts.emitOpenlineageToken) } : {}),\n ...(opts.emitOpenlineageProducer\n ? { producer: String(opts.emitOpenlineageProducer) }\n : {}),\n ...(Array.isArray(opts.emitOpenlineageHeader) && opts.emitOpenlineageHeader.length > 0\n ? { headerArgs: opts.emitOpenlineageHeader as string[] }\n : {}),\n ...(opts.emitOpenlineageRunId ? { runId: String(opts.emitOpenlineageRunId) } : {}),\n ...(opts.emitOpenlineageDryRun ? { dryRun: true } : {}),\n ...(opts.emitOpenlineageEventsOut\n ? { eventsOutPath: String(opts.emitOpenlineageEventsOut) }\n : {}),\n ...(opts.emitOpenlineageEventsOutFormat\n ? {\n eventsOutFormat: validateEventsOutFormat(\n String(opts.emitOpenlineageEventsOutFormat),\n ),\n }\n : {}),\n ...(opts.emitOpenlineageSkipEmpty ? { skipEmpty: true } : {}),\n ...(typeof opts.emitOpenlineageMinEvents === 'number' &&\n opts.emitOpenlineageMinEvents > 0\n ? { minEvents: opts.emitOpenlineageMinEvents }\n : {}),\n sourceHint,\n });\n if (!outcome.ok) {\n process.exitCode = 2;\n }\n }\n return;\n }\n if (!opts.source) throw new Error('Either --source or --dbt-manifest is required.');\n const model = await loadModel(String(opts.source));\n const fullGraph = lineage.buildLineageGraph(model);\n\n const direction = String(opts.direction ?? 'both').toLowerCase() as\n | 'upstream'\n | 'downstream'\n | 'both';\n let graph = fullGraph;\n let focus: string | undefined;\n if (opts.fqn) {\n focus = String(opts.fqn);\n const depth: number = typeof opts.depth === 'number' ? opts.depth : Infinity;\n if (direction === 'upstream') {\n const keep = new Set([focus, ...lineage.upstreamOf(fullGraph, focus, depth)]);\n graph = subsetGraph(fullGraph, keep);\n } else if (direction === 'downstream') {\n const keep = new Set([focus, ...lineage.downstreamOf(fullGraph, focus, depth)]);\n graph = subsetGraph(fullGraph, keep);\n } else {\n graph = lineage.sliceAround(fullGraph, focus, depth);\n }\n }\n\n const fmt = String(opts.format ?? 'mermaid').toLowerCase() as lineage.LineageFormat;\n if (!['mermaid', 'dot', 'json', 'markdown'].includes(fmt)) {\n throw new Error(`Unknown --format: ${fmt}. Use mermaid | dot | json | markdown.`);\n }\n const renderOpts: lineage.RenderOptions = {\n ...(focus ? { focus } : {}),\n ...(typeof opts.maxEdges === 'number' ? { maxEdges: opts.maxEdges } : {}),\n ...(opts.columns ? { includeColumns: true } : {}),\n };\n const payload = lineage.renderLineage(graph, fmt, renderOpts);\n\n if (opts.out) {\n const out = path.resolve(String(opts.out));\n await fs.mkdir(path.dirname(out), { recursive: true });\n await fs.writeFile(out, payload + (payload.endsWith('\\n') ? '' : '\\n'), 'utf8');\n console.error(\n `Wrote ${out} (${payload.length} bytes, ${graph.nodes.length} nodes, ${graph.edges.length} edges).`,\n );\n } else {\n process.stdout.write(payload + (payload.endsWith('\\n') ? '' : '\\n'));\n }\n await runExplain(\n {\n feature: 'lineage.explain',\n systemPrompt:\n 'You are a Databricks data-platform architect explaining a lineage graph. Describe the dominant data-flow shape, point out hot or fragile nodes, and recommend any decomposition / sharding the graph suggests.',\n },\n opts as { explain?: boolean },\n () => {\n const focused = focus ? ` (focused on ${focus}, direction=${direction})` : '';\n const summary = `Lineage graph${focused}: ${graph.nodes.length} nodes, ${graph.edges.length} edges.`;\n const sample = graph.edges\n .slice(0, 40)\n .map((e) => ` - ${e.from} ${e.kind === 'READS_FROM' ? '->' : '=>'} ${e.to}`);\n return [\n summary,\n '',\n 'Edges (up to 40):',\n ...sample,\n '',\n 'Narrate this graph in plain English.',\n ].join('\\n');\n },\n );\n });\n attachExplainFlag(cmd);\n return cmd;\n}\n\nfunction subsetGraph(graph: lineage.LineageGraph, keep: Set<string>): lineage.LineageGraph {\n return {\n nodes: graph.nodes.filter((n) => keep.has(n.fqn)),\n edges: graph.edges.filter((e) => keep.has(e.from) && keep.has(e.to)),\n };\n}\n\nasync function loadModel(sourcePath: string): Promise<DatabricksObject[]> {\n if (sourcePath.endsWith('.ddtpac')) {\n const c = await pac.readPac(sourcePath);\n return c.model;\n }\n const loaded = await loadProject(sourcePath);\n return await parseProjectModel(loaded);\n}\n\n/**\n * Walk a project model collecting `{objectFqn, lineage}` pairs for every\n * object whose body parses through CLL.1's `extractColumnLineage`. Covers\n * VIEW / MATERIALIZED_VIEW / STREAMING_TABLE — the three Databricks object\n * types whose `query: SqlExpression` is what downstream consumers depend\n * on for column-level lineage. CLL.4 entry point.\n */\nfunction collectColumnLineageInputs(\n model: DatabricksObject[],\n): columnLineage.ColumnLineageDagInput[] {\n const inputs: columnLineage.ColumnLineageDagInput[] = [];\n const matchTypes = new Set<string>(['VIEW', 'MATERIALIZED_VIEW', 'STREAMING_TABLE']);\n for (const obj of model) {\n if (!matchTypes.has(obj.objectType)) continue;\n const query = (obj as unknown as { query?: string }).query;\n if (typeof query !== 'string' || query.length === 0) continue;\n const fqn = formatFqn(obj.fqn);\n const lineage = columnLineage.extractColumnLineage(query);\n inputs.push({ objectFqn: fqn, lineage });\n }\n return inputs;\n}\n\nfunction formatFqn(fqn: unknown): string {\n if (typeof fqn === 'string') return fqn;\n if (fqn && typeof fqn === 'object') {\n const f = fqn as { catalog?: string; schema?: string; name?: string; database?: string };\n return [f.catalog ?? f.database, f.schema, f.name].filter(Boolean).join('.');\n }\n return '<unknown>';\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport {\n diagnostics,\n interop,\n loadProject,\n pac,\n parseProjectModel,\n type DatabricksObject,\n} from '@ddt-tools/core';\nimport { attachExplainFlag, runExplain } from '../util/ai-explain.js';\n\n/**\n * `ddt diagnose` — project-level health report. Bundles lint, lineage\n * smells (orphan / no-downstream / hot-table / cycle), object smells\n * (`SELECT *` in views, large tables without CLUSTER BY / Z-ORDER,\n * streaming tables without watermark / checkpoint, deletion-vector\n * gaps) and cost smells (long delta.logRetentionDuration). Every\n * finding ships with a **reasoning** line explaining *why* it matters.\n *\n * Mirrors `sdt diagnose`.\n */\nexport function diagnoseCommand(): Command {\n const cmd = new Command('diagnose');\n cmd\n .description(\n 'Project-level health report: lint + lineage smells + object smells + cost smells, with reasoning.',\n )\n .requiredOption('--source <path>', '.ddtproj or .ddtpac to analyze.')\n .option(\n '--category <c>',\n 'Filter to one category: lint | lineage | smell | cost | dim-modeling.',\n )\n .option(\n '--min-severity <s>',\n 'Filter to a minimum severity: error | warning | info. Default info (everything).',\n 'info',\n )\n .option(\n '--format <fmt>',\n 'table | json | markdown | sarif. sarif emits SARIF 2.1.0 for GitHub code-scanning / Azure DevOps. Default table.',\n 'table',\n )\n .option('-o, --out <path>', 'Output file path. Defaults to stdout.')\n .action(\n async (opts: {\n source: string;\n category?: string;\n minSeverity?: string;\n format?: string;\n out?: string;\n explain?: boolean;\n }) => {\n const sourcePath = String(opts.source);\n const model = await loadModel(sourcePath);\n const report = diagnostics.analyzeProject(model, {\n source: sourcePath,\n ...(opts.category\n ? { category: String(opts.category) as diagnostics.DiagnosticCategory }\n : {}),\n ...(opts.minSeverity\n ? { minSeverity: String(opts.minSeverity) as diagnostics.DiagnosticSeverity }\n : {}),\n });\n\n const fmt = String(opts.format ?? 'table').toLowerCase();\n let payload: string;\n if (fmt === 'json') {\n payload = JSON.stringify(report, null, 2);\n } else if (fmt === 'markdown') {\n payload = renderReportMarkdown(report);\n } else if (fmt === 'sarif') {\n payload = JSON.stringify(interop.diagnosticReportToSarif(report), null, 2);\n } else if (fmt === 'table') {\n payload = diagnostics.formatReport(report);\n } else {\n throw new Error(`Unknown --format: ${fmt}. Use table | json | markdown | sarif.`);\n }\n\n if (opts.out) {\n const out = path.resolve(String(opts.out));\n await fs.mkdir(path.dirname(out), { recursive: true });\n await fs.writeFile(out, payload + (payload.endsWith('\\n') ? '' : '\\n'), 'utf8');\n console.error(\n `Wrote ${out} (${payload.length} bytes, ${report.findings.length} finding(s)).`,\n );\n } else {\n process.stdout.write(payload + (payload.endsWith('\\n') ? '' : '\\n'));\n }\n\n if (report.totals.error > 0) process.exitCode = 1;\n\n await runExplain({ feature: 'diagnose.explain' }, opts, () => buildDiagnosePrompt(report));\n },\n );\n attachExplainFlag(cmd);\n return cmd;\n}\n\nfunction buildDiagnosePrompt(report: diagnostics.DiagnosticReport): string {\n const lines: string[] = [];\n lines.push(`Source: ${report.source || '(unknown)'}`);\n lines.push(\n `Totals: ${report.totals.error} error, ${report.totals.warning} warning, ${report.totals.info} info`,\n );\n lines.push('');\n const top = report.findings\n .slice()\n .sort((a, b) => sevWeight(b.severity) - sevWeight(a.severity))\n .slice(0, 40);\n lines.push(`Top ${top.length} findings (highest severity first):`);\n for (const d of top) {\n lines.push(`- [${d.severity}] ${d.id} · ${d.fqn || '(project)'} — ${d.message}`);\n }\n if (report.findings.length > top.length) {\n lines.push(`(… ${report.findings.length - top.length} more truncated)`);\n }\n lines.push('');\n lines.push(\n 'Explain the dominant themes, what they suggest about the project health, and the highest-leverage fixes the team should tackle first.',\n );\n return lines.join('\\n');\n}\n\nfunction sevWeight(s: diagnostics.DiagnosticSeverity): number {\n return s === 'error' ? 3 : s === 'warning' ? 2 : 1;\n}\n\nfunction renderReportMarkdown(report: diagnostics.DiagnosticReport): string {\n const lines: string[] = [];\n lines.push(`# Diagnostic report — \\`${report.source || '(no source)'}\\``);\n lines.push('');\n lines.push(`Generated: ${report.generatedAt}`);\n lines.push('');\n lines.push(\n `**Totals:** ${report.totals.error} error · ${report.totals.warning} warning · ${report.totals.info} info`,\n );\n lines.push('');\n lines.push('## By category');\n lines.push('');\n lines.push('| Category | Count |');\n lines.push('|---|---|');\n for (const [k, v] of Object.entries(report.byCategory)) {\n if (v > 0) lines.push(`| ${k} | ${v} |`);\n }\n lines.push('');\n if (report.findings.length === 0) {\n lines.push('_No findings._');\n return lines.join('\\n');\n }\n lines.push('## Findings');\n lines.push('');\n for (const d of report.findings) {\n const glyph = d.severity === 'error' ? '🛑' : d.severity === 'warning' ? '⚠️' : 'ℹ️';\n lines.push(`### ${glyph} \\`${d.id}\\` — ${d.fqn || '(project)'}`);\n lines.push('');\n lines.push(`**${d.message}**`);\n lines.push('');\n lines.push(`*Why:* ${d.reasoning}`);\n lines.push('');\n lines.push(`*Suggestion:* ${d.suggestion}`);\n lines.push('');\n if (d.related && d.related.length > 0) {\n lines.push(\n `*Related:* ${d.related\n .slice(0, 5)\n .map((r) => `\\`${r}\\``)\n .join(', ')}`,\n );\n lines.push('');\n }\n }\n return lines.join('\\n');\n}\n\nasync function loadModel(sourcePath: string): Promise<DatabricksObject[]> {\n if (sourcePath.endsWith('.ddtpac')) {\n const c = await pac.readPac(sourcePath);\n return c.model;\n }\n const loaded = await loadProject(sourcePath);\n return await parseProjectModel(loaded);\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport {\n ai,\n aiReview,\n loadProject,\n pac,\n parseProjectModel,\n review,\n type DatabricksObject,\n} from '@ddt-tools/core';\nimport { attachExplainFlag, runExplain } from '../util/ai-explain.js';\n\n/**\n * `ddt review` — senior-DBA Markdown report. Mirrors `sdt review`.\n *\n * Default mode (project health): pure composition of existing modules.\n *\n * `--senior-dba` mode (AI Phase 4): takes a compare-result JSON + a\n * safety-summary JSON + optional target-metadata snapshot + truncated\n * DDL preview, asks the configured AI provider for a senior-DBA\n * verdict, and emits the parsed result as Markdown (or JSON via\n * `--format json`).\n */\nexport function reviewCommand(): Command {\n const cmd = new Command('review');\n cmd\n .description(\n 'Senior-DBA-style health report (lint + lineage + smell + cost + safety, with reasoning).',\n )\n .option('--source <path>', '.ddtproj or .ddtpac to analyze (project-health mode).')\n .option('-o, --out <path>', 'Output file path. Defaults to stdout.')\n .option(\n '--senior-dba',\n 'AI-driven senior-DBA review of a deploy diff (requires --diff and --safety).',\n false,\n )\n .option(\n '--diff <path>',\n 'JSON file with compare summary { added, removed, modified, addedSample, removedSample, modifiedSample }.',\n )\n .option(\n '--safety <path>',\n 'JSON file with safety summary { unrecoverable, destructive, expensive, warning, sample }.',\n )\n .option(\n '--target-meta <path>',\n 'Optional file with target-metadata prose (existing tables, recent deploys, role grants).',\n )\n .option('--ddl <path>', 'Optional truncated DDL preview file.')\n .option('--format <fmt>', 'Output format: markdown | json. Default markdown.', 'markdown')\n .option(\n '--ai-max-spend <usd>',\n \"Refuse the AI call if today's estimated spend ≥ this (USD). 0 = no cap.\",\n '0',\n )\n .action(\n async (opts: {\n source?: string;\n out?: string;\n explain?: boolean;\n seniorDba?: boolean;\n diff?: string;\n safety?: string;\n targetMeta?: string;\n ddl?: string;\n format?: string;\n aiMaxSpend?: string;\n }) => {\n if (opts.seniorDba) {\n await runSeniorDbaReview(opts, 'ddt');\n return;\n }\n if (!opts.source) {\n throw new Error('--source is required in the default (project-health) mode.');\n }\n const sourcePath = String(opts.source);\n const model = await loadModel(sourcePath);\n const md = review.renderReviewReport(model, { source: sourcePath });\n await emit(md, opts.out);\n await runExplain(\n {\n feature: 'review.explain',\n systemPrompt:\n 'You are a Databricks principal engineer giving a senior-architect walkthrough of an automated review report. Summarize the headline themes, recommend the top 3 follow-ups in order of leverage, and call out anything a junior reviewer might miss.',\n },\n opts,\n () =>\n `Review report follows:\\n\\n${md}\\n\\nNarrate this report for a teammate who has not read it.`,\n );\n },\n );\n attachExplainFlag(cmd);\n return cmd;\n}\n\nexport async function runSeniorDbaReview(\n opts: {\n diff?: string;\n safety?: string;\n targetMeta?: string;\n ddl?: string;\n format?: string;\n out?: string;\n aiMaxSpend?: string;\n },\n toolName: 'sdt' | 'ddt',\n): Promise<void> {\n if (!opts.diff || !opts.safety) {\n throw new Error('--senior-dba requires both --diff and --safety (JSON files).');\n }\n const [diff, safety, targetMeta, ddl] = await Promise.all([\n readJson(opts.diff),\n readJson(opts.safety),\n opts.targetMeta\n ? fs.readFile(path.resolve(opts.targetMeta), 'utf8')\n : Promise.resolve<string | undefined>(undefined),\n opts.ddl\n ? fs.readFile(path.resolve(opts.ddl), 'utf8')\n : Promise.resolve<string | undefined>(undefined),\n ]);\n\n const compareSummary = normalizeCompareSummary(diff);\n const safetySummary = normalizeSafetySummary(safety);\n\n const result = await aiReview.runSeniorDbaReview(\n {\n compareSummary,\n safetySummary,\n ...(targetMeta ? { targetMetadata: targetMeta } : {}),\n ...(ddl ? { ddlPreview: ddl } : {}),\n },\n {\n completeFn: async (user, system) => {\n const r = await ai.complete(\n [\n { role: 'system', content: system },\n { role: 'user', content: user },\n ],\n {\n feature: 'review.senior-dba',\n maxSpendUsd: Number(opts.aiMaxSpend ?? '0') || 0,\n },\n );\n return r.text;\n },\n },\n toolName,\n );\n\n const format = String(opts.format ?? 'markdown').toLowerCase();\n const payload =\n format === 'json'\n ? JSON.stringify({ ...result, rawModelText: undefined }, null, 2)\n : aiReview.renderSeniorDbaReviewMarkdown(result, toolName);\n await emit(payload, opts.out);\n if (result.verdict === 'request_changes' && !opts.out) {\n process.exitCode = 2;\n }\n}\n\nfunction normalizeCompareSummary(raw: unknown): aiReview.CompareSummaryInput {\n const o = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>;\n const num = (k: string) => (typeof o[k] === 'number' ? (o[k] as number) : 0);\n const arr = (k: string) =>\n Array.isArray(o[k])\n ? (o[k] as unknown[]).filter((x): x is string => typeof x === 'string')\n : undefined;\n return {\n added: num('added'),\n removed: num('removed'),\n modified: num('modified'),\n ...(arr('addedSample') ? { addedSample: arr('addedSample') } : {}),\n ...(arr('removedSample') ? { removedSample: arr('removedSample') } : {}),\n ...(arr('modifiedSample') ? { modifiedSample: arr('modifiedSample') } : {}),\n };\n}\n\nfunction normalizeSafetySummary(raw: unknown): aiReview.SafetySummaryInput {\n const o = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>;\n const num = (k: string) => (typeof o[k] === 'number' ? (o[k] as number) : 0);\n const sample = Array.isArray(o.sample)\n ? (o.sample as unknown[]).filter((x): x is string => typeof x === 'string')\n : undefined;\n return {\n unrecoverable: num('unrecoverable'),\n destructive: num('destructive'),\n expensive: num('expensive'),\n warning: num('warning'),\n ...(sample ? { sample } : {}),\n };\n}\n\nasync function readJson(p: string): Promise<unknown> {\n const raw = await fs.readFile(path.resolve(p), 'utf8');\n return JSON.parse(raw);\n}\n\nasync function loadModel(sourcePath: string): Promise<DatabricksObject[]> {\n if (sourcePath.endsWith('.ddtpac')) {\n const c = await pac.readPac(sourcePath);\n return c.model;\n }\n const loaded = await loadProject(sourcePath);\n return await parseProjectModel(loaded);\n}\n\nasync function emit(payload: string, out: unknown): Promise<void> {\n if (out) {\n const p = path.resolve(String(out));\n await fs.mkdir(path.dirname(p), { recursive: true });\n await fs.writeFile(p, payload + (payload.endsWith('\\n') ? '' : '\\n'), 'utf8');\n console.error(`Wrote ${p} (${payload.length} bytes).`);\n } else {\n process.stdout.write(payload + (payload.endsWith('\\n') ? '' : '\\n'));\n }\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport {\n loadProject,\n pac,\n parseProjectModel,\n review,\n type DatabricksObject,\n} from '@ddt-tools/core';\nimport { attachExplainFlag, runExplain } from '../util/ai-explain.js';\n\n/**\n * `ddt impact <fqn>` — single-FQN blast-radius. Mirrors `sdt impact`.\n */\nexport function impactCommand(): Command {\n const cmd = new Command('impact');\n cmd\n .description(\n 'Single-FQN blast-radius: who feeds it, who reads from it, what findings apply to it.',\n )\n .argument('<fqn>', 'Fully-qualified name to analyze (e.g. main.gold.orders).')\n .requiredOption('--source <path>', '.ddtproj or .ddtpac to analyze.')\n .option('-o, --out <path>', 'Output file path. Defaults to stdout.')\n .action(async (fqn: string, opts: { source: string; out?: string; explain?: boolean }) => {\n const sourcePath = String(opts.source);\n const model = await loadModel(sourcePath);\n const md = review.renderImpactReport(model, String(fqn), { source: sourcePath });\n await emit(md, opts.out);\n await runExplain(\n {\n feature: 'impact.explain',\n systemPrompt:\n 'You are a senior Databricks data engineer explaining an impact analysis to a developer who is about to change one object. Be very direct about the blast radius and what they should test before merging.',\n },\n opts,\n () =>\n `Impact report for ${fqn} follows:\\n\\n${md}\\n\\nExplain the blast radius and what the engineer should pay attention to.`,\n );\n });\n attachExplainFlag(cmd);\n return cmd;\n}\n\nasync function loadModel(sourcePath: string): Promise<DatabricksObject[]> {\n if (sourcePath.endsWith('.ddtpac')) {\n const c = await pac.readPac(sourcePath);\n return c.model;\n }\n const loaded = await loadProject(sourcePath);\n return await parseProjectModel(loaded);\n}\n\nasync function emit(payload: string, out: unknown): Promise<void> {\n if (out) {\n const p = path.resolve(String(out));\n await fs.mkdir(path.dirname(p), { recursive: true });\n await fs.writeFile(p, payload + (payload.endsWith('\\n') ? '' : '\\n'), 'utf8');\n console.error(`Wrote ${p} (${payload.length} bytes).`);\n } else {\n process.stdout.write(payload + (payload.endsWith('\\n') ? '' : '\\n'));\n }\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { attachExplainFlag, runExplain } from '../util/ai-explain.js';\n\ninterface HistoryEntry {\n sqlText?: string;\n durationMs?: number;\n}\n\n/**\n * `ddt cost-estimate` — heuristic DBU estimator for a generated\n * migration script.\n *\n * Approach mirrors `sdt cost-estimate` but uses Databricks DBU\n * pricing instead of Snowflake credits. The \"cluster size\" ladder\n * maps to common SQL warehouse sizes (XS/S/M/L/XL/2XL/3XL).\n *\n * Ranges are conservative. Actual DBU consumption depends on file\n * counts, Z-ORDER state, and Photon enablement that this static\n * pass can't see — we say so in the output.\n */\nexport function costEstimateCommand(): Command {\n const cmd = new Command('cost-estimate');\n cmd\n .description('Heuristic Databricks-DBU estimate for a generated migration script.')\n .requiredOption(\n '--script <path>',\n 'Path to a generated migration script (.sql) from `ddt publish`.',\n )\n .option(\n '--warehouse-size <size>',\n 'SQL warehouse size: 2X-Small | X-Small | Small | Medium | Large | X-Large | 2X-Large | 3X-Large | 4X-Large.',\n 'Small',\n )\n .option('--format <fmt>', 'table | json | markdown. Default table.', 'table')\n .option('-o, --out <path>', 'Write output to file. Defaults to stdout.')\n .option(\n '--calibrate-from <path>',\n 'AI Phase 6 calibration: a JSON file of QueryHistoryEntry[] from prior deploys. Each historic statement is classified against the same cost-classes; classes with ≥3 samples adopt empirical min/max duration in place of the heuristic range.',\n )\n .action(\n async (opts: {\n script: string;\n warehouseSize?: string;\n format?: string;\n out?: string;\n calibrateFrom?: string;\n explain?: boolean;\n }) => {\n const sql = await fs.readFile(path.resolve(String(opts.script)), 'utf8');\n const whRaw = String(opts.warehouseSize ?? 'Small');\n const wh = whRaw as WarehouseSize;\n if (!(wh in DBU_PER_HOUR)) {\n throw new Error(\n `Unknown --warehouse-size: ${whRaw}. Use one of ${Object.keys(DBU_PER_HOUR).join(' | ')}.`,\n );\n }\n let calibration: ClassCalibration | undefined;\n if (opts.calibrateFrom) {\n const histRaw = await fs.readFile(path.resolve(String(opts.calibrateFrom)), 'utf8');\n const parsed = JSON.parse(histRaw);\n const entries: HistoryEntry[] = Array.isArray(parsed)\n ? parsed\n : Array.isArray(parsed.entries)\n ? parsed.entries\n : [];\n calibration = buildCalibration(entries);\n }\n const report = estimateCost(sql, wh, calibration);\n const fmt = String(opts.format ?? 'table').toLowerCase();\n let payload: string;\n if (fmt === 'json') {\n payload = JSON.stringify(report, null, 2);\n } else if (fmt === 'markdown') {\n payload = renderMarkdown(report);\n } else {\n payload = renderTable(report);\n }\n if (opts.out) {\n const p = path.resolve(String(opts.out));\n await fs.mkdir(path.dirname(p), { recursive: true });\n await fs.writeFile(p, payload + (payload.endsWith('\\n') ? '' : '\\n'), 'utf8');\n console.error(`Wrote ${p}.`);\n } else {\n process.stdout.write(payload + (payload.endsWith('\\n') ? '' : '\\n'));\n }\n await runExplain(\n {\n feature: 'cost-estimate.explain',\n systemPrompt:\n 'You are a Databricks cost engineer. Walk the team through this DBU estimate: what is the dominant cost driver, what does the range mean in practice, and what knobs (warehouse size, Photon, sequencing, off-peak timing) would meaningfully reduce it.',\n },\n opts,\n () =>\n `Cost estimate (JSON) follows:\\n\\n${JSON.stringify(report, null, 2)}\\n\\nNarrate this for a teammate.`,\n );\n },\n );\n attachExplainFlag(cmd);\n return cmd;\n}\n\ntype WarehouseSize =\n | '2X-Small'\n | 'X-Small'\n | 'Small'\n | 'Medium'\n | 'Large'\n | 'X-Large'\n | '2X-Large'\n | '3X-Large'\n | '4X-Large';\n\nconst DBU_PER_HOUR: Record<WarehouseSize, number> = {\n '2X-Small': 4,\n 'X-Small': 6,\n Small: 12,\n Medium: 24,\n Large: 40,\n 'X-Large': 80,\n '2X-Large': 144,\n '3X-Large': 272,\n '4X-Large': 528,\n};\n\ninterface CostClass {\n id: string;\n description: string;\n minSeconds: number;\n maxSeconds: number;\n test: (sql: string) => boolean;\n}\n\nconst COST_CLASSES: CostClass[] = [\n {\n id: 'table-rebuild',\n description: 'CREATE OR REPLACE TABLE or CTAS — rewrites the entire table',\n minSeconds: 30,\n maxSeconds: 1800,\n test: (s) =>\n /CREATE\\s+(?:OR\\s+REPLACE\\s+)?TABLE\\s+.+\\s+AS\\s+SELECT/i.test(s) ||\n /CREATE\\s+OR\\s+REPLACE\\s+TABLE\\b/i.test(s),\n },\n {\n id: 'optimize',\n description: 'OPTIMIZE / OPTIMIZE … ZORDER BY — compact + cluster',\n minSeconds: 60,\n maxSeconds: 3600,\n test: (s) => /^\\s*OPTIMIZE\\b/i.test(s),\n },\n {\n id: 'vacuum',\n description: 'VACUUM — removes old files',\n minSeconds: 30,\n maxSeconds: 600,\n test: (s) => /^\\s*VACUUM\\b/i.test(s),\n },\n {\n id: 'add-column',\n description: 'ALTER TABLE ADD COLUMN — metadata-only',\n minSeconds: 1,\n maxSeconds: 5,\n test: (s) => /ALTER\\s+TABLE\\b.*\\bADD\\s+COLUMN\\b/i.test(s),\n },\n {\n id: 'drop-column',\n description: 'ALTER TABLE DROP COLUMN — metadata-only (DV-enabled)',\n minSeconds: 1,\n maxSeconds: 5,\n test: (s) => /ALTER\\s+TABLE\\b.*\\bDROP\\s+COLUMN\\b/i.test(s),\n },\n {\n id: 'alter-type-narrowing',\n description: 'ALTER COLUMN TYPE — may require rewrite',\n minSeconds: 30,\n maxSeconds: 600,\n test: (s) => /ALTER\\s+TABLE\\b.*\\bALTER\\s+COLUMN\\b.*\\bTYPE\\b/i.test(s),\n },\n {\n id: 'create-view',\n description: 'CREATE OR REPLACE VIEW — metadata-only',\n minSeconds: 1,\n maxSeconds: 3,\n test: (s) => /CREATE\\s+(?:OR\\s+REPLACE\\s+)?VIEW\\b/i.test(s) && !/MATERIALIZED/i.test(s),\n },\n {\n id: 'create-mv',\n description: 'CREATE MATERIALIZED VIEW — initial materialisation',\n minSeconds: 60,\n maxSeconds: 3600,\n test: (s) => /CREATE\\s+(?:OR\\s+REPLACE\\s+)?MATERIALIZED\\s+VIEW\\b/i.test(s),\n },\n {\n id: 'create-streaming',\n description: 'CREATE STREAMING TABLE — initial population',\n minSeconds: 60,\n maxSeconds: 1800,\n test: (s) => /CREATE\\s+(?:OR\\s+REPLACE\\s+)?STREAMING\\s+TABLE\\b/i.test(s),\n },\n {\n id: 'create-pipeline',\n description: 'CREATE PIPELINE — DLT initial run',\n minSeconds: 120,\n maxSeconds: 3600,\n test: (s) => /CREATE\\s+(?:OR\\s+REPLACE\\s+)?PIPELINE\\b/i.test(s),\n },\n {\n id: 'set-tblproperties',\n description: 'ALTER TABLE … SET TBLPROPERTIES — metadata-only',\n minSeconds: 1,\n maxSeconds: 3,\n test: (s) => /ALTER\\s+TABLE\\b.*\\bSET\\s+TBLPROPERTIES\\b/i.test(s),\n },\n {\n id: 'drop',\n description: 'DROP statement — metadata-only',\n minSeconds: 1,\n maxSeconds: 3,\n test: (s) => /^\\s*DROP\\s+/i.test(s),\n },\n {\n id: 'grant',\n description: 'GRANT / REVOKE — metadata-only',\n minSeconds: 1,\n maxSeconds: 2,\n test: (s) => /^\\s*(?:GRANT|REVOKE)\\s+/i.test(s),\n },\n {\n id: 'comment',\n description: 'COMMENT-only statement — free',\n minSeconds: 0,\n maxSeconds: 0,\n test: (s) =>\n s\n .replace(/--[^\\n]*/g, '')\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, '')\n .trim().length === 0,\n },\n];\n\ninterface CostReport {\n warehouseSize: WarehouseSize;\n dbuPerHour: number;\n totalStatements: number;\n classifiedStatements: number;\n unknownStatements: number;\n perClass: Array<{\n id: string;\n description: string;\n count: number;\n minSeconds: number;\n maxSeconds: number;\n minDbu: number;\n maxDbu: number;\n /** When set, the per-statement range came from this many empirical samples. */\n calibratedFromSamples?: number;\n }>;\n totals: {\n minSeconds: number;\n maxSeconds: number;\n minDbu: number;\n maxDbu: number;\n };\n}\n\n/**\n * AI Phase 6 calibration — per-class empirical duration ranges harvested\n * from prior `QueryHistoryEntry[]` (typed in `@ddt-tools/core/queryHistory`).\n * When a class has at least 3 historic samples, its heuristic min/max is\n * replaced with the observed min/max. Classes that fall back to the\n * heuristic are flagged in the report so the user can see what was\n * calibrated.\n */\ninterface ClassCalibration {\n perClass: Record<string, { sampleSize: number; minSeconds: number; maxSeconds: number }>;\n}\n\nfunction buildCalibration(entries: HistoryEntry[]): ClassCalibration {\n const samples = new Map<string, number[]>();\n for (const e of entries) {\n const sql = typeof e.sqlText === 'string' ? e.sqlText : '';\n const dur = typeof e.durationMs === 'number' ? e.durationMs : NaN;\n if (!sql || !isFinite(dur) || dur <= 0) continue;\n const matched = COST_CLASSES.find((c) => c.test(sql));\n if (!matched) continue;\n const arr = samples.get(matched.id) ?? [];\n arr.push(dur / 1000);\n samples.set(matched.id, arr);\n }\n const perClass: ClassCalibration['perClass'] = {};\n for (const [id, durs] of samples) {\n if (durs.length < 3) continue;\n durs.sort((a, b) => a - b);\n perClass[id] = {\n sampleSize: durs.length,\n minSeconds: Math.max(1, Math.round(durs[0]!)),\n maxSeconds: Math.max(1, Math.round(durs[durs.length - 1]!)),\n };\n }\n return { perClass };\n}\n\nfunction estimateCost(\n sql: string,\n warehouseSize: WarehouseSize,\n calibration?: ClassCalibration,\n): CostReport {\n const statements = splitStatements(sql);\n const classCounts = new Map<string, number>();\n let classifiedStatements = 0;\n let unknownStatements = 0;\n for (const stmt of statements) {\n const matched = COST_CLASSES.find((c) => c.test(stmt));\n if (matched) {\n classCounts.set(matched.id, (classCounts.get(matched.id) ?? 0) + 1);\n classifiedStatements++;\n } else if (stmt.trim().length > 0) {\n unknownStatements++;\n }\n }\n const dbuPerHour = DBU_PER_HOUR[warehouseSize];\n const perClass = COST_CLASSES.filter((c) => (classCounts.get(c.id) ?? 0) > 0).map((c) => {\n const count = classCounts.get(c.id) ?? 0;\n const cal = calibration?.perClass[c.id];\n const minSecondsPerStmt = cal ? cal.minSeconds : c.minSeconds;\n const maxSecondsPerStmt = cal ? cal.maxSeconds : c.maxSeconds;\n const minSeconds = minSecondsPerStmt * count;\n const maxSeconds = maxSecondsPerStmt * count;\n return {\n id: c.id,\n description: c.description,\n count,\n minSeconds,\n maxSeconds,\n minDbu: (minSeconds / 3600) * dbuPerHour,\n maxDbu: (maxSeconds / 3600) * dbuPerHour,\n ...(cal ? { calibratedFromSamples: cal.sampleSize } : {}),\n };\n });\n const totals = perClass.reduce(\n (acc, c) => ({\n minSeconds: acc.minSeconds + c.minSeconds,\n maxSeconds: acc.maxSeconds + c.maxSeconds,\n minDbu: acc.minDbu + c.minDbu,\n maxDbu: acc.maxDbu + c.maxDbu,\n }),\n { minSeconds: 0, maxSeconds: 0, minDbu: 0, maxDbu: 0 },\n );\n return {\n warehouseSize,\n dbuPerHour,\n totalStatements: statements.length,\n classifiedStatements,\n unknownStatements,\n perClass,\n totals,\n };\n}\n\nfunction splitStatements(sql: string): string[] {\n return sql\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, '')\n .split(/;\\s*$/m)\n .map((s) => s.trim())\n .filter(Boolean);\n}\n\nfunction renderTable(r: CostReport): string {\n const lines: string[] = [];\n lines.push(`Cost estimate — warehouse=${r.warehouseSize} (${r.dbuPerHour} DBU/hour)`);\n lines.push('');\n lines.push(\n ` Statements: ${r.totalStatements} (${r.classifiedStatements} classified, ${r.unknownStatements} unknown).`,\n );\n lines.push('');\n const idW = Math.max(20, ...r.perClass.map((c) => c.id.length));\n for (const c of r.perClass) {\n lines.push(\n ` ${c.id.padEnd(idW)} ×${String(c.count).padStart(4)} ≈ ${c.minDbu.toFixed(3)} – ${c.maxDbu.toFixed(3)} DBU`,\n );\n }\n lines.push('');\n lines.push(\n ` TOTAL ≈ ${r.totals.minDbu.toFixed(3)} – ${r.totals.maxDbu.toFixed(3)} DBU`,\n );\n lines.push(` TOTAL (duration estimate) ≈ ${r.totals.minSeconds}s – ${r.totals.maxSeconds}s`);\n lines.push('');\n lines.push(' Note: ranges are heuristic. Actual DBU consumption depends on file count,');\n lines.push(' Z-ORDER state, deletion-vector enablement, and Photon. Treat the upper bound');\n lines.push(' as a pessimistic ceiling, not a likely outcome.');\n return lines.join('\\n');\n}\n\nfunction renderMarkdown(r: CostReport): string {\n const lines: string[] = [];\n lines.push(`# Cost estimate`);\n lines.push('');\n lines.push(`**Warehouse:** ${r.warehouseSize} (${r.dbuPerHour} DBU/hour)`);\n lines.push(\n `**Statements:** ${r.totalStatements} total, ${r.classifiedStatements} classified, ${r.unknownStatements} unknown`,\n );\n lines.push('');\n lines.push('## Estimate by statement class');\n lines.push('');\n lines.push('| Class | Count | DBU range |');\n lines.push('|---|---|---|');\n for (const c of r.perClass) {\n lines.push(\n `| \\`${c.id}\\` (${c.description}) | ${c.count} | ${c.minDbu.toFixed(3)} – ${c.maxDbu.toFixed(3)} |`,\n );\n }\n lines.push('');\n lines.push(\n `**Total:** ${r.totals.minDbu.toFixed(3)} – ${r.totals.maxDbu.toFixed(3)} DBU (${r.totals.minSeconds}–${r.totals.maxSeconds}s)`,\n );\n lines.push('');\n lines.push(\n '> Ranges are heuristic. Actual DBU consumption depends on file count, Z-ORDER state, DV enablement, and Photon.',\n );\n return lines.join('\\n');\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport {\n CompareEngine,\n PacSource,\n ProjectSource,\n loadProject,\n pac,\n parseProjectModel,\n review,\n safety,\n type CompareSource,\n type DatabricksObject,\n} from '@ddt-tools/core';\nimport { attachExplainFlag, runExplain } from '../util/ai-explain.js';\nimport { attachRelatedOptions } from '../util/help-catalog.js';\n\n/**\n * `ddt pr-comment` — Markdown PR sticky-comment from a source↔target\n * compare. Mirrors `sdt pr-comment`.\n */\nexport function prCommentCommand(): Command {\n const cmd = new Command('pr-comment');\n cmd\n .description(\n 'Generate a Markdown PR comment from a source↔target compare (diff + safety + health).',\n )\n .requiredOption('--source <path>', '.ddtproj or .ddtpac (the desired state).')\n .requiredOption('--target <path>', '.ddtproj or .ddtpac (the current state).')\n .option('-o, --out <path>', 'Output file path. Defaults to stdout.')\n .action(async (opts: { source: string; target: string; out?: string; explain?: boolean }) => {\n const sourcePath = String(opts.source);\n const targetPath = String(opts.target);\n const engine = new CompareEngine();\n const src: CompareSource = sourcePath.endsWith('.ddtpac')\n ? new PacSource(sourcePath, 'source')\n : new ProjectSource(sourcePath, 'source');\n const tgt: CompareSource = targetPath.endsWith('.ddtpac')\n ? new PacSource(targetPath, 'target')\n : new ProjectSource(targetPath, 'target');\n const result = await engine.compare(src, tgt);\n const assessment = safety.assess(result);\n const model = await loadModel(sourcePath);\n const md = review.renderPrComment(model, result, assessment, { source: sourcePath });\n if (opts.out) {\n const p = path.resolve(String(opts.out));\n await fs.mkdir(path.dirname(p), { recursive: true });\n await fs.writeFile(p, md + (md.endsWith('\\n') ? '' : '\\n'), 'utf8');\n console.error(`Wrote ${p} (${md.length} bytes).`);\n } else {\n process.stdout.write(md + (md.endsWith('\\n') ? '' : '\\n'));\n }\n await runExplain(\n {\n feature: 'pr-comment.explain',\n systemPrompt:\n 'You are a release manager preparing the human summary for a code-review comment. Distill the structured PR comment into 3-5 sentences a reviewer can read in 30 seconds. Lead with the riskiest change.',\n },\n opts,\n () =>\n `PR comment payload follows:\\n\\n${md}\\n\\nWrite a tight executive summary a busy reviewer will appreciate.`,\n );\n });\n attachExplainFlag(cmd);\n attachRelatedOptions(cmd, [\n 'compare.ignoreCase',\n 'compare.ignoreComments',\n 'compare.ignoreFormattingDifferences',\n 'compare.excludeObjectTypes',\n 'compare.excludeObjectPatterns',\n 'compare.includeObjectPatterns',\n ]);\n return cmd;\n}\n\nasync function loadModel(sourcePath: string): Promise<DatabricksObject[]> {\n if (sourcePath.endsWith('.ddtpac')) {\n const c = await pac.readPac(sourcePath);\n return c.model;\n }\n const loaded = await loadProject(sourcePath);\n return await parseProjectModel(loaded);\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\n\n/**\n * `ddt template <kind> <name>` — schema cookbook generator for\n * Databricks Unity Catalog. Mirrors `sdt template` with idioms\n * adapted to Delta + UC (CLUSTER BY, deletion vectors, Photon, no\n * CONSTRAINT NOT ENFORCED — UC doesn't have that flag).\n *\n * Supported kinds:\n * - `scd1` — SCD type-1 (overwrite, no history).\n * - `scd2` — SCD type-2 (history-preserving).\n * - `scd3` — SCD type-3 (one previous value).\n * - `scd4` — SCD type-4 (current + history table).\n * - `scd6` — Hybrid 1+2+3.\n * - `star` — Star schema fact + N dimensions.\n * - `fact` — Fact table only, with FKs to named dims.\n * - `scd2-merge` — Canonical MERGE for SCD2 load.\n * - `current-view` — CREATE VIEW WHERE is_current = TRUE.\n * - `time-series` — Clustered time-series with retention.\n * - `audit` — Append-only audit log.\n */\nexport function templateCommand(): Command {\n const cmd = new Command('template');\n cmd\n .description(\n 'Scaffold a common schema pattern (scd1|scd2|scd3|scd4|scd6|star|fact|scd2-merge|current-view|time-series|audit). Writes .sql files into <out>/.',\n )\n .argument(\n '<kind>',\n 'Pattern to scaffold: scd1 | scd2 | scd3 | scd4 | scd6 | star | fact | scd2-merge | current-view | time-series | audit',\n )\n .argument('<name>', 'Base object name (e.g. CUSTOMER, ORDERS).')\n .option('--catalog <catalog>', 'UC catalog name. Default main.', 'main')\n .option('--schema <schema>', 'Schema name. Default gold.', 'gold')\n .option('-o, --out <path>', 'Output directory. Default <kind>-<name>/.')\n .option(\n '--dims <dims>',\n '[star|fact] Comma-separated dimension names. Default: customer,product,date.',\n 'customer,product,date',\n )\n .option(\n '--track <cols>',\n '[scd3|scd6] Comma-separated columns to track previous-values for. Default: attribute_1.',\n 'attribute_1',\n )\n .option(\n '--source <fqn>',\n '[scd2-merge] Source/staging table fully-qualified name. Default main.gold.<name>_stage.',\n )\n .option('--retention-days <n>', '[time-series] Retention window in days. Default 90.', '90')\n .action(async (kindArg, nameArg, opts) => {\n const kind = String(kindArg).toLowerCase();\n const name = String(nameArg);\n const catalog = String(opts.catalog);\n const schema = String(opts.schema);\n const out = opts.out\n ? path.resolve(String(opts.out))\n : path.resolve(`${kind}-${name.toLowerCase()}`);\n await fs.mkdir(out, { recursive: true });\n\n const ctx = { catalog, schema, name };\n let files: Record<string, string>;\n const trackCols = String(opts.track)\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean);\n const dims = String(opts.dims)\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean);\n if (kind === 'scd1') files = renderScd1(ctx);\n else if (kind === 'scd2') files = renderScd2(ctx);\n else if (kind === 'scd3') files = renderScd3(ctx, trackCols);\n else if (kind === 'scd4') files = renderScd4(ctx);\n else if (kind === 'scd6') files = renderScd6(ctx, trackCols);\n else if (kind === 'star') files = renderStar(ctx, dims);\n else if (kind === 'fact') files = renderFact(ctx, dims);\n else if (kind === 'scd2-merge')\n files = renderScd2Merge(\n ctx,\n opts.source ? String(opts.source) : `${catalog}.${schema}.${name.toLowerCase()}_stage`,\n );\n else if (kind === 'current-view') files = renderCurrentView(ctx);\n else if (kind === 'time-series') files = renderTimeSeries(ctx, Number(opts.retentionDays));\n else if (kind === 'audit') files = renderAudit(ctx);\n else\n throw new Error(\n `Unknown template kind: ${kind}. Use scd1 | scd2 | scd3 | scd4 | scd6 | star | fact | scd2-merge | current-view | time-series | audit.`,\n );\n\n for (const [rel, contents] of Object.entries(files)) {\n const filePath = path.join(out, rel);\n await fs.mkdir(path.dirname(filePath), { recursive: true });\n await fs.writeFile(filePath, contents, 'utf8');\n console.error(\n ` wrote ${path.relative(process.cwd(), filePath)} (${contents.length} bytes)`,\n );\n }\n console.error(\n `Done. ${Object.keys(files).length} file(s) written to ${path.relative(process.cwd(), out)}.`,\n );\n });\n return cmd;\n}\n\ninterface Ctx {\n catalog: string;\n schema: string;\n name: string;\n}\n\nfunction header(why: string): string {\n return `-- Generated by \\`ddt template\\`. Why this pattern is the right shape:\\n-- ${why}\\n--\\n-- Edit freely; this is just a starting point.\\n\\n`;\n}\n\nfunction renderScd1(c: Ctx): Record<string, string> {\n const lower = c.name.toLowerCase();\n return {\n [`${c.catalog}/${c.schema}/tables/${lower}.sql`]:\n header(\n `SCD1 overwrites the row in place when an attribute changes. No history is\n-- preserved. Use this when downstream only cares about the *current* state.\n-- load_ts/updated_ts give you minimal auditability without history-table cost.`,\n ) +\n `CREATE OR REPLACE TABLE ${c.catalog}.${c.schema}.${lower} (\n ${lower}_sk BIGINT GENERATED ALWAYS AS IDENTITY COMMENT 'Surrogate key — stable across overwrites',\n ${lower}_bk STRING NOT NULL COMMENT 'Business key',\n attribute_1 STRING COMMENT 'Replace with real columns',\n attribute_2 STRING COMMENT 'Replace with real columns',\n load_ts TIMESTAMP NOT NULL DEFAULT current_timestamp() COMMENT 'When the row was first inserted',\n updated_ts TIMESTAMP COMMENT 'When the row was last overwritten'\n)\nUSING DELTA\nCLUSTER BY (${lower}_bk)\nTBLPROPERTIES ('delta.enableDeletionVectors' = 'true')\nCOMMENT 'SCD1 dimension — overwrite-on-change. No history kept; join on ${lower}_bk.';\n`,\n };\n}\n\nfunction renderScd2(c: Ctx): Record<string, string> {\n const lower = c.name.toLowerCase();\n return {\n [`${c.catalog}/${c.schema}/tables/${lower}.sql`]:\n header(\n `SCD2 preserves every historical version of a row by closing the previous\n-- row's VALID_TO when the natural key reappears with new attribute values.\n-- Use this when downstream analytics needs \"what did this row look like on date X\".`,\n ) +\n `CREATE OR REPLACE TABLE ${c.catalog}.${c.schema}.${lower} (\n ${lower}_sk BIGINT GENERATED ALWAYS AS IDENTITY COMMENT 'Surrogate key',\n ${lower}_bk STRING NOT NULL COMMENT 'Business key',\n attribute_1 STRING COMMENT 'Replace with real columns',\n attribute_2 STRING COMMENT 'Replace with real columns',\n valid_from TIMESTAMP NOT NULL COMMENT 'When this version became current',\n valid_to TIMESTAMP COMMENT 'When this version was superseded; NULL while current',\n is_current BOOLEAN NOT NULL COMMENT 'TRUE only on the latest row per BK',\n load_ts TIMESTAMP NOT NULL DEFAULT current_timestamp() COMMENT 'Insertion timestamp'\n)\nUSING DELTA\nCLUSTER BY (${lower}_bk, valid_from)\nTBLPROPERTIES ('delta.enableDeletionVectors' = 'true')\nCOMMENT 'SCD2 dimension — preserves history. Join on (${lower}_bk, is_current=TRUE) for current state.';\n`,\n };\n}\n\nfunction renderScd3(c: Ctx, tracked: string[]): Record<string, string> {\n const lower = c.name.toLowerCase();\n const cols = (tracked.length ? tracked : ['attribute_1']).map((t) => t.toLowerCase());\n const prevCols = cols\n .map(\n (t) =>\n ` prev_${t} STRING COMMENT 'Prior value of ${t}'`,\n )\n .join(',\\n');\n return {\n [`${c.catalog}/${c.schema}/tables/${lower}.sql`]:\n header(\n `SCD3 keeps the current value plus one prior value per tracked column. Use\n-- this when downstream needs \"current vs immediately prior\" but doesn't need\n-- the full history. Cheaper than SCD2 but lossy beyond one change.`,\n ) +\n `CREATE OR REPLACE TABLE ${c.catalog}.${c.schema}.${lower} (\n ${lower}_sk BIGINT GENERATED ALWAYS AS IDENTITY COMMENT 'Surrogate key',\n ${lower}_bk STRING NOT NULL COMMENT 'Business key',\n${cols.map((t) => ` ${t} STRING COMMENT 'Current value'`).join(',\\n')},\n${prevCols},\n prev_changed_ts TIMESTAMP COMMENT 'When prior values were captured',\n load_ts TIMESTAMP NOT NULL DEFAULT current_timestamp() COMMENT 'Insertion timestamp',\n updated_ts TIMESTAMP COMMENT 'When this row was last overwritten'\n)\nUSING DELTA\nCLUSTER BY (${lower}_bk)\nTBLPROPERTIES ('delta.enableDeletionVectors' = 'true')\nCOMMENT 'SCD3 dimension — current + one prior value for ${cols.join(', ')}.';\n`,\n };\n}\n\nfunction renderScd4(c: Ctx): Record<string, string> {\n const lower = c.name.toLowerCase();\n return {\n [`${c.catalog}/${c.schema}/tables/${lower}.sql`]:\n header(\n `SCD4 keeps a small, fast \"current\" table for joins and a separate history\n-- table for slow analytics. Use this when current-state lookups are hot\n-- (every fact query joins to it) and you want the join table skinny.`,\n ) +\n `CREATE OR REPLACE TABLE ${c.catalog}.${c.schema}.${lower} (\n ${lower}_sk BIGINT GENERATED ALWAYS AS IDENTITY COMMENT 'Surrogate key',\n ${lower}_bk STRING NOT NULL COMMENT 'Business key',\n attribute_1 STRING COMMENT 'Replace with real columns',\n attribute_2 STRING COMMENT 'Replace with real columns',\n load_ts TIMESTAMP NOT NULL DEFAULT current_timestamp() COMMENT 'When the row was inserted',\n updated_ts TIMESTAMP COMMENT 'When the row was last overwritten'\n)\nUSING DELTA\nCLUSTER BY (${lower}_bk)\nTBLPROPERTIES ('delta.enableDeletionVectors' = 'true')\nCOMMENT 'SCD4 current-state table. Pair with ${lower}_history for change tracking.';\n`,\n [`${c.catalog}/${c.schema}/tables/${lower}_history.sql`]:\n header(\n `Companion history table for SCD4. Rows are appended (never updated) when\n-- the current table is overwritten — same columns plus a changed_ts so you\n-- can replay \"what did this BK look like at time T\".`,\n ) +\n `CREATE OR REPLACE TABLE ${c.catalog}.${c.schema}.${lower}_history (\n ${lower}_history_sk BIGINT GENERATED ALWAYS AS IDENTITY COMMENT 'Surrogate id for each historical snapshot',\n ${lower}_bk STRING NOT NULL COMMENT 'Business key',\n attribute_1 STRING COMMENT 'Snapshot of column at changed_ts',\n attribute_2 STRING COMMENT 'Snapshot of column at changed_ts',\n changed_ts TIMESTAMP NOT NULL COMMENT 'When this snapshot was taken',\n load_ts TIMESTAMP NOT NULL DEFAULT current_timestamp() COMMENT 'When the row was appended'\n)\nUSING DELTA\nCLUSTER BY (${lower}_bk, changed_ts)\nTBLPROPERTIES ('delta.enableDeletionVectors' = 'true', 'delta.enableChangeDataFeed' = 'true')\nCOMMENT 'SCD4 history-side. Append-only snapshots of ${lower}; reconstruct as-of state via window functions.';\n`,\n };\n}\n\nfunction renderScd6(c: Ctx, tracked: string[]): Record<string, string> {\n const lower = c.name.toLowerCase();\n const cols = (tracked.length ? tracked : ['attribute_1']).map((t) => t.toLowerCase());\n const prevCols = cols\n .map(\n (t) =>\n ` prev_${t} STRING COMMENT 'Prior value of ${t}'`,\n )\n .join(',\\n');\n return {\n [`${c.catalog}/${c.schema}/tables/${lower}.sql`]:\n header(\n `SCD6 = 1 + 2 + 3 hybrid. Full SCD2 history (rows per version), SCD3\n-- \"current vs prior\" lookback on hot columns, and SCD1 \"current value\"\n-- denormalized onto every historical row. Heavyweight; use when downstream\n-- consumers ask both \"what was it at time T?\" and \"what's the current value\n-- for the BK on this old row?\" in the same query.`,\n ) +\n `CREATE OR REPLACE TABLE ${c.catalog}.${c.schema}.${lower} (\n ${lower}_sk BIGINT GENERATED ALWAYS AS IDENTITY COMMENT 'Surrogate key — unique per version',\n ${lower}_bk STRING NOT NULL COMMENT 'Business key — stable across versions',\n${cols.map((t) => ` ${t} STRING COMMENT 'Value on THIS version'`).join(',\\n')},\n${cols.map((t) => ` current_${t} STRING COMMENT 'Current value for the BK (SCD1 denorm)'`).join(',\\n')},\n${prevCols},\n valid_from TIMESTAMP NOT NULL COMMENT 'When this version became current',\n valid_to TIMESTAMP COMMENT 'When this version was superseded; NULL while current',\n is_current BOOLEAN NOT NULL COMMENT 'TRUE only on the latest row per BK',\n load_ts TIMESTAMP NOT NULL DEFAULT current_timestamp() COMMENT 'Insertion timestamp'\n)\nUSING DELTA\nCLUSTER BY (${lower}_bk, valid_from)\nTBLPROPERTIES ('delta.enableDeletionVectors' = 'true')\nCOMMENT 'SCD6 dimension — hybrid 1+2+3. Heavy but answers every common BI question without re-joining.';\n`,\n };\n}\n\nfunction renderStar(c: Ctx, dims: string[]): Record<string, string> {\n const fact = c.name.toLowerCase();\n const out: Record<string, string> = {};\n for (const d of dims) {\n const lower = d.toLowerCase();\n out[`${c.catalog}/${c.schema}/tables/dim_${lower}.sql`] =\n header(`Dimension table — describes the WHAT. Joined by the fact via dim_${lower}_sk.`) +\n `CREATE OR REPLACE TABLE ${c.catalog}.${c.schema}.dim_${lower} (\n dim_${lower}_sk BIGINT GENERATED ALWAYS AS IDENTITY COMMENT 'Surrogate key',\n ${lower}_bk STRING NOT NULL COMMENT 'Business key',\n ${lower}_name STRING COMMENT 'Replace with real attributes',\n country STRING COMMENT 'Example attribute'\n)\nUSING DELTA\nCLUSTER BY (${lower}_bk)\nTBLPROPERTIES ('delta.enableDeletionVectors' = 'true')\nCOMMENT 'Dimension table for the ${fact} star schema.';\n`;\n }\n out[`${c.catalog}/${c.schema}/tables/fact_${fact}.sql`] =\n header(\n `Fact table — the WHO/WHAT/WHEN/HOW-MUCH. One row per business event.\n-- Surrogate-key FKs to every dimension; measure columns hold the numbers.\n-- CLUSTER BY (event_ts) keeps recent-event scans cheap (Delta data skipping).`,\n ) +\n `CREATE OR REPLACE TABLE ${c.catalog}.${c.schema}.fact_${fact} (\n fact_${fact}_sk BIGINT GENERATED ALWAYS AS IDENTITY COMMENT 'Surrogate key',\n${dims.map((d) => ` dim_${d.toLowerCase()}_sk BIGINT COMMENT 'FK to dim_${d.toLowerCase()}'`).join(',\\n')},\n event_ts TIMESTAMP NOT NULL COMMENT 'When the event occurred',\n measure_amount DECIMAL(38,4) COMMENT 'Primary measure',\n measure_quantity BIGINT COMMENT 'Secondary measure',\n load_ts TIMESTAMP NOT NULL DEFAULT current_timestamp() COMMENT 'Insertion timestamp'\n)\nUSING DELTA\nCLUSTER BY (event_ts)\nTBLPROPERTIES ('delta.enableDeletionVectors' = 'true', 'delta.enableChangeDataFeed' = 'true')\nCOMMENT 'Fact table for the ${fact} star. CLUSTER BY event_ts + Photon = cheap recent-window scans.';\n`;\n return out;\n}\n\nfunction renderFact(c: Ctx, dims: string[]): Record<string, string> {\n const fact = c.name.toLowerCase();\n return {\n [`${c.catalog}/${c.schema}/tables/fact_${fact}.sql`]:\n header(\n `Fact-only template — assumes the named dimensions already exist. Use this\n-- when adding a new fact to an existing star, rather than scaffolding the\n-- dims a second time. FKs follow the dim_<name>_sk convention.`,\n ) +\n `CREATE OR REPLACE TABLE ${c.catalog}.${c.schema}.fact_${fact} (\n fact_${fact}_sk BIGINT GENERATED ALWAYS AS IDENTITY COMMENT 'Surrogate key',\n${dims.map((d) => ` dim_${d.toLowerCase()}_sk BIGINT COMMENT 'FK to dim_${d.toLowerCase()}'`).join(',\\n')},\n event_ts TIMESTAMP NOT NULL COMMENT 'When the event occurred',\n measure_amount DECIMAL(38,4) COMMENT 'Primary measure',\n measure_quantity BIGINT COMMENT 'Secondary measure',\n load_ts TIMESTAMP NOT NULL DEFAULT current_timestamp() COMMENT 'Insertion timestamp'\n)\nUSING DELTA\nCLUSTER BY (event_ts)\nTBLPROPERTIES ('delta.enableDeletionVectors' = 'true', 'delta.enableChangeDataFeed' = 'true')\nCOMMENT 'Fact table fact_${fact}. Add to an existing star — dimensions assumed to exist.';\n`,\n };\n}\n\nfunction renderScd2Merge(c: Ctx, source: string): Record<string, string> {\n const lower = c.name.toLowerCase();\n return {\n [`${c.catalog}/${c.schema}/scripts/merge_${lower}.sql`]:\n header(\n `Canonical SCD2 load. Step 1 closes the prior row when the BK reappears with\n-- different attributes (sets valid_to + is_current=FALSE). Step 2 inserts the\n-- new version. Both steps in one MERGE WHEN MATCHED / WHEN NOT MATCHED.\n-- Source: ${source}.`,\n ) +\n `-- Single-statement SCD2 merge.\n-- Databricks MERGE supports multiple WHEN MATCHED clauses — we use one to close\n-- the old row, then a follow-up INSERT to write the new version (the same MERGE\n-- cannot both UPDATE the prior row AND INSERT the new row for the same source\n-- key, so we split).\n\nMERGE INTO ${c.catalog}.${c.schema}.${lower} AS tgt\nUSING (\n SELECT\n src.${lower}_bk,\n src.attribute_1,\n src.attribute_2\n FROM ${source} AS src\n) AS src\nON tgt.${lower}_bk = src.${lower}_bk\n AND tgt.is_current = TRUE\nWHEN MATCHED\n AND (NOT (tgt.attribute_1 <=> src.attribute_1)\n OR NOT (tgt.attribute_2 <=> src.attribute_2))\n THEN UPDATE SET\n valid_to = current_timestamp(),\n is_current = FALSE;\n\nINSERT INTO ${c.catalog}.${c.schema}.${lower} (\n ${lower}_bk, attribute_1, attribute_2,\n valid_from, valid_to, is_current\n)\nSELECT\n src.${lower}_bk,\n src.attribute_1,\n src.attribute_2,\n current_timestamp(),\n NULL,\n TRUE\nFROM ${source} AS src\nLEFT JOIN ${c.catalog}.${c.schema}.${lower} AS tgt\n ON tgt.${lower}_bk = src.${lower}_bk\n AND tgt.is_current = TRUE\nWHERE tgt.${lower}_bk IS NULL\n OR NOT (tgt.attribute_1 <=> src.attribute_1)\n OR NOT (tgt.attribute_2 <=> src.attribute_2);\n`,\n };\n}\n\nfunction renderCurrentView(c: Ctx): Record<string, string> {\n const lower = c.name.toLowerCase();\n return {\n [`${c.catalog}/${c.schema}/views/v_${lower}_current.sql`]:\n header(\n `Current-state view over an SCD2 table. Lets downstream consumers join on\n-- one canonical \"current row per BK\" target without remembering the\n-- is_current predicate. Cheap — Delta filter-pushdown handles it.`,\n ) +\n `CREATE OR REPLACE VIEW ${c.catalog}.${c.schema}.v_${lower}_current\nCOMMENT 'Current rows from ${lower} (SCD2). Join here instead of filtering is_current manually.'\nAS\nSELECT *\nFROM ${c.catalog}.${c.schema}.${lower}\nWHERE is_current = TRUE;\n`,\n };\n}\n\nfunction renderTimeSeries(c: Ctx, retentionDays: number): Record<string, string> {\n const lower = c.name.toLowerCase();\n return {\n [`${c.catalog}/${c.schema}/tables/${lower}.sql`]:\n header(\n `Time-series table — append-only, clustered by event timestamp so recent-event\n-- scans prune to a small number of files. delta.logRetentionDuration bounds\n-- Time-Travel storage cost; aged-out rows must be archived elsewhere.`,\n ) +\n `CREATE OR REPLACE TABLE ${c.catalog}.${c.schema}.${lower} (\n event_id BIGINT GENERATED ALWAYS AS IDENTITY COMMENT 'Surrogate id',\n event_ts TIMESTAMP NOT NULL COMMENT 'When the event occurred',\n event_type STRING COMMENT 'Discriminator',\n entity_id STRING COMMENT 'Foreign key to the entity the event is about',\n payload MAP<STRING, STRING> COMMENT 'Event-specific payload',\n ingested_ts TIMESTAMP NOT NULL DEFAULT current_timestamp() COMMENT 'When DDT loaded the row'\n)\nUSING DELTA\nCLUSTER BY (event_ts)\nTBLPROPERTIES (\n 'delta.enableDeletionVectors' = 'true',\n 'delta.logRetentionDuration' = 'interval ${Math.max(7, Math.min(retentionDays, 365))} days'\n)\nCOMMENT 'Time-series ${lower}. Aged out beyond delta.logRetentionDuration; archive separately if you need longer history.';\n`,\n };\n}\n\nfunction renderAudit(c: Ctx): Record<string, string> {\n const lower = c.name.toLowerCase();\n return {\n [`${c.catalog}/${c.schema}/tables/${lower}_audit.sql`]:\n header(\n `Audit log — append-only by convention. INSERT-only role grants enforce the\n-- \"append-only\" property; this table itself doesn't block updates, but the\n-- grants do.`,\n ) +\n `CREATE OR REPLACE TABLE ${c.catalog}.${c.schema}.${lower}_audit (\n audit_id BIGINT GENERATED ALWAYS AS IDENTITY COMMENT 'Surrogate id',\n audit_ts TIMESTAMP NOT NULL DEFAULT current_timestamp() COMMENT 'When the event was logged',\n actor STRING NOT NULL COMMENT 'Who performed the action',\n action STRING NOT NULL COMMENT 'What happened',\n target STRING COMMENT 'What it was performed on',\n details MAP<STRING, STRING> COMMENT 'Free-form payload — keep it small'\n)\nUSING DELTA\nCLUSTER BY (audit_ts)\nTBLPROPERTIES ('delta.enableDeletionVectors' = 'true')\nCOMMENT 'Audit log for ${lower}. Append-only by convention — GRANT INSERT only to writer roles.';\n`,\n };\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { loadProject, pac, parseProjectModel, type DatabricksObject } from '@ddt-tools/core';\n\n/**\n * `ddt anonymize` — generate column-mask DDL for PII columns\n * discovered in a project model. Pairs with the L012 `pii-without-mask`\n * lint rule.\n *\n * Databricks Unity Catalog uses `ALTER TABLE ... ALTER COLUMN ... SET\n * MASK <function>` (column masks via UC functions). This command\n * generates:\n * 1. A UC FUNCTION per PII category (mask_email, mask_phone, …)\n * that returns the value unchanged when current_user() is in an\n * allow-list, else returns a masked variant.\n * 2. ALTER COLUMN SET MASK statements wiring each PII column to\n * its category's function.\n *\n * Output is conservative: default allow-list is just the deploy\n * service-principal; production access should be added before\n * applying.\n */\nexport function anonymizeCommand(): Command {\n const cmd = new Command('anonymize');\n cmd\n .description('Generate column-mask DDL for PII columns detected in the project model.')\n .requiredOption('--source <path>', '.ddtproj or .ddtpac to analyze.')\n .option(\n '--unmasked-user <name>',\n \"User / service-principal that sees unmasked values. Default 'ddt-deploy'.\",\n 'ddt-deploy',\n )\n .option(\n '--mask-catalog <catalog>',\n 'Catalog the mask functions live in. Default: same catalog as the columns.',\n )\n .option('-o, --out <path>', 'Output file path. Default: ./anonymize.sql in CWD.')\n .action(async (opts) => {\n const sourcePath = String(opts.source);\n const model = await loadModel(sourcePath);\n const unmaskedUser = String(opts.unmaskedUser);\n const maskCatalog = opts.maskCatalog ? String(opts.maskCatalog) : undefined;\n const candidates = collectPiiColumns(model);\n if (candidates.length === 0) {\n console.error('No PII columns detected (heuristic on column names).');\n return;\n }\n const sql = renderAnonymizeSql(candidates, unmaskedUser, maskCatalog);\n const outPath = opts.out ? path.resolve(String(opts.out)) : path.resolve('anonymize.sql');\n await fs.mkdir(path.dirname(outPath), { recursive: true });\n await fs.writeFile(outPath, sql, 'utf8');\n console.error(`Wrote ${outPath} (${candidates.length} column(s), ${sql.length} bytes).`);\n console.error(\n 'Review the user allow-list before applying. Default fully masks values from every user except the one passed in.',\n );\n });\n return cmd;\n}\n\ninterface PiiColumn {\n catalog: string;\n schema: string;\n table: string;\n column: string;\n category: 'email' | 'phone' | 'name' | 'dob' | 'ssn' | 'address' | 'credit-card' | 'generic';\n}\n\nfunction collectPiiColumns(model: readonly DatabricksObject[]): PiiColumn[] {\n const out: PiiColumn[] = [];\n for (const o of model) {\n if (o.objectType !== 'MANAGED_TABLE' && o.objectType !== 'EXTERNAL_TABLE') continue;\n const rec = o as unknown as Record<string, unknown>;\n const cols = rec.columns as Array<{ name: string }> | undefined;\n if (!Array.isArray(cols)) continue;\n const catalog = o.fqn.database ?? 'main';\n const schema = o.fqn.schema ?? 'default';\n for (const c of cols) {\n const category = classify(c.name);\n if (category) out.push({ catalog, schema, table: o.fqn.name, column: c.name, category });\n }\n }\n return out;\n}\n\nfunction classify(name: string): PiiColumn['category'] | undefined {\n const lower = name.toLowerCase();\n if (/(^|_)email(_|$)/.test(lower)) return 'email';\n if (/(^|_)(phone|mobile|cell)(_|$)/.test(lower)) return 'phone';\n if (/(^|_)(first_name|last_name|full_name|surname|given_name)(_|$)/.test(lower)) return 'name';\n if (/(^|_)(dob|birth_date|date_of_birth)(_|$)/.test(lower)) return 'dob';\n if (/(^|_)ssn(_|$)/.test(lower) || /(^|_)tax_id(_|$)/.test(lower)) return 'ssn';\n if (/(^|_)(address|street|zip_code|postal_code|postcode)(_|$)/.test(lower)) return 'address';\n if (/(^|_)(credit_card|card_number)(_|$)/.test(lower)) return 'credit-card';\n return undefined;\n}\n\nfunction renderAnonymizeSql(\n cols: PiiColumn[],\n unmaskedUser: string,\n maskCatalogOverride: string | undefined,\n): string {\n const lines: string[] = [];\n lines.push(`-- Generated by \\`ddt anonymize\\`.`);\n lines.push(\n `-- Edit the user allow-list before applying. Default: only ${unmaskedUser} sees unmasked values.`,\n );\n lines.push('');\n // Group columns by mask-function catalog. If override, all go there;\n // else group by each column's own catalog.\n const byCatalog = new Map<string, PiiColumn[]>();\n for (const c of cols) {\n const target = maskCatalogOverride ?? c.catalog;\n const arr = byCatalog.get(target) ?? [];\n arr.push(c);\n byCatalog.set(target, arr);\n }\n // For each catalog that hosts mask functions, emit one FUNCTION per\n // category present.\n for (const [catalog, catalogCols] of byCatalog) {\n const cats = new Set(catalogCols.map((c) => c.category));\n lines.push(`-- ── Mask functions in catalog \\`${catalog}\\`.security ──`);\n lines.push(`CREATE SCHEMA IF NOT EXISTS ${catalog}.security;`);\n lines.push('');\n for (const cat of cats) {\n lines.push(\n `CREATE OR REPLACE FUNCTION ${catalog}.security.mask_${cat.replace(/-/g, '_')}(val STRING)`,\n );\n lines.push(` RETURNS STRING`);\n lines.push(` RETURN CASE`);\n lines.push(\n ` WHEN is_member('${unmaskedUser}') OR current_user() = '${unmaskedUser}' THEN val`,\n );\n lines.push(` ELSE ${maskExpression(cat)}`);\n lines.push(` END;`);\n lines.push('');\n }\n }\n // Apply masks.\n lines.push('-- Apply masks to columns');\n for (const c of cols) {\n const fnCatalog = maskCatalogOverride ?? c.catalog;\n const fnName = `${fnCatalog}.security.mask_${c.category.replace(/-/g, '_')}`;\n lines.push(\n `ALTER TABLE ${c.catalog}.${c.schema}.${c.table} ALTER COLUMN ${c.column} SET MASK ${fnName};`,\n );\n }\n lines.push('');\n return lines.join('\\n') + '\\n';\n}\n\nfunction maskExpression(cat: PiiColumn['category']): string {\n switch (cat) {\n case 'email':\n return `regexp_replace(val, '^(.).*(@.*)$', '$1***$2')`;\n case 'phone':\n return `concat('***-***-', right(val, 4))`;\n case 'ssn':\n return `concat('***-**-', right(val, 4))`;\n case 'credit-card':\n return `concat('****-****-****-', right(val, 4))`;\n case 'dob':\n return `concat(left(val, 4), '-XX-XX')`;\n case 'name':\n case 'address':\n case 'generic':\n default:\n return `sha2(val, 256)`;\n }\n}\n\nasync function loadModel(sourcePath: string): Promise<DatabricksObject[]> {\n if (sourcePath.endsWith('.ddtpac')) {\n const c = await pac.readPac(sourcePath);\n return c.model;\n }\n const loaded = await loadProject(sourcePath);\n return await parseProjectModel(loaded);\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport {\n loadProject,\n parseProjectModel,\n testFramework,\n createConnection,\n getProfile,\n} from '@ddt-tools/core';\n\n/**\n * `ddt test` — declarative test framework. Mirrors `sdt test`.\n */\nexport function testCommand(): Command {\n const cmd = new Command('test').description(\n 'Declarative tests (unique / not_null / accepted_values / relationships / expression) compiled from YAML to SQL.',\n );\n\n cmd\n .command('list')\n .description('Enumerate test files and their test counts.')\n .requiredOption('-p, --project <path>', 'Path to the .ddtproj file.')\n .action(async (opts) => {\n const loaded = await loadProject(String(opts.project));\n const files = await testFramework.discoverTests(loaded.rootDir);\n if (files.length === 0) {\n console.log(\n 'No tests found. Add files under <project>/tests/<catalog>/<schema>/<table>.test.yaml.',\n );\n return;\n }\n for (const f of files) {\n console.log(` ${f.fqn.padEnd(40)} ${String(f.tests.length).padStart(3)} test(s)`);\n for (const t of f.tests) {\n const cols =\n 'columns' in t\n ? `(${(t.columns ?? []).join(', ')})`\n : 'column' in t\n ? `(${t.column})`\n : '';\n console.log(` - ${t.kind}${cols}${t.name ? ` ${t.name}` : ''}`);\n }\n }\n console.log('');\n console.log(\n `${files.length} file(s), ${files.reduce((acc, f) => acc + f.tests.length, 0)} test(s) total.`,\n );\n });\n\n cmd\n .command('render')\n .description('Compile every test YAML into SQL assertions. Offline; no workspace contact.')\n .requiredOption('-p, --project <path>', 'Path to the .ddtproj file.')\n .option('-o, --out <path>', 'Write to file. Defaults to stdout.')\n .action(async (opts) => {\n const loaded = await loadProject(String(opts.project));\n const files = await testFramework.discoverTests(loaded.rootDir);\n const sql = testFramework.renderAllTests(files);\n if (opts.out) {\n const out = path.resolve(String(opts.out));\n await fs.mkdir(path.dirname(out), { recursive: true });\n await fs.writeFile(out, sql, 'utf8');\n console.error(\n `Wrote ${out} (${sql.length} bytes, ${files.reduce((a, f) => a + f.tests.length, 0)} test(s)).`,\n );\n } else {\n process.stdout.write(sql);\n }\n });\n\n cmd\n .command('run')\n .description(\n 'Execute every test assertion against a live Databricks workspace and report pass/fail. ' +\n 'Exits 2 when any error-severity test fails. Pro tier — composes DCM item 5 (data-quality expectations) ' +\n 'with the existing dbt-test parity framework.',\n )\n .requiredOption('-p, --project <path>', 'Path to the .ddtproj file.')\n .requiredOption('-c, --connection <profile>', 'Connection profile name.')\n .option(\n '--select <pattern>',\n 'Filter tests to files whose FQN matches a glob pattern. E.g. \"main.public.*\".',\n )\n .option('--fail-fast', 'Stop on the first error-severity failure.', false)\n .option(\n '--sample <n>',\n 'Cap failing-row samples captured per test. Default 10. 0 to skip.',\n '10',\n )\n .option(\n '--update-snapshots',\n 'TEST.3: overwrite every saved snapshot under .ddt/tests/__snapshots__/ with the live rows. Use when intentional schema change makes drift expected.',\n false,\n )\n .option('--format <fmt>', 'Output format: text | json. Default text.', 'text')\n .option('-o, --out <path>', 'Write report to a file instead of stdout.')\n .action(async (opts) => {\n const loaded = await loadProject(String(opts.project));\n let files = await testFramework.discoverTests(loaded.rootDir);\n if (opts.select) {\n const re = globToRegex(String(opts.select));\n files = files.filter((f) => re.test(f.fqn));\n }\n if (files.length === 0) {\n console.log(\n 'No tests found. Add files under <project>/tests/<catalog>/<schema>/<table>.test.yaml.',\n );\n return;\n }\n const profile = await getProfile(String(opts.connection));\n const conn = createConnection(profile);\n console.error(`test run: connecting to ${profile.auth.host}…`);\n await conn.connect();\n const snapshotsDir = path.join(loaded.rootDir, '.ddt', 'tests', '__snapshots__');\n const snapshotStorage: testFramework.SnapshotStorage = {\n async read(name) {\n try {\n return await fs.readFile(path.join(snapshotsDir, `${name}.json`), 'utf8');\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === 'ENOENT') return null;\n throw e;\n }\n },\n async write(name, body) {\n await fs.mkdir(snapshotsDir, { recursive: true });\n await fs.writeFile(path.join(snapshotsDir, `${name}.json`), body, 'utf8');\n },\n };\n let report;\n try {\n report = await testFramework.runTestFiles(files, conn, {\n failFast: opts.failFast === true,\n failingRowSampleCap: Number(opts.sample ?? '10'),\n snapshotStorage,\n updateSnapshots: opts.updateSnapshots === true,\n });\n } finally {\n await conn.disconnect().catch(() => undefined);\n }\n const output =\n String(opts.format).toLowerCase() === 'json'\n ? testFramework.renderJsonReport(report)\n : testFramework.renderTextReport(report);\n if (opts.out) {\n const out = path.resolve(String(opts.out));\n await fs.mkdir(path.dirname(out), { recursive: true });\n await fs.writeFile(out, output, 'utf8');\n console.error(\n `Wrote ${out} — ${report.summary.pass} pass / ${report.summary.fail} fail / ${report.summary.error} error.`,\n );\n } else {\n process.stdout.write(output);\n }\n if (report.summary.blocking) {\n process.exitCode = 2;\n }\n });\n\n cmd\n .command('coverage')\n .description(\n 'Report which project objects have at least one declarative test (TEST.4). ' +\n 'Offline; no workspace contact. Emits a Markdown table (default) or JSON.',\n )\n .requiredOption('-p, --project <path>', 'Path to the .ddtproj file.')\n .option('--format <fmt>', 'Output format: text | json. Default text.', 'text')\n .option('-o, --out <path>', 'Write report to a file instead of stdout.')\n .action(async (opts) => {\n const loaded = await loadProject(String(opts.project));\n const files = await testFramework.discoverTests(loaded.rootDir);\n const model = await parseProjectModel(loaded);\n const testable = new Set<string>([\n 'TABLE',\n 'MANAGED_TABLE',\n 'EXTERNAL_TABLE',\n 'VIEW',\n 'MATERIALIZED_VIEW',\n 'STREAMING_TABLE',\n ]);\n const fqns: string[] = [];\n for (const obj of model) {\n if (!testable.has(obj.objectType)) continue;\n const cat = obj.fqn.database;\n const sc = obj.fqn.schema;\n if (!cat || !sc) continue;\n fqns.push(`${cat}.${sc}.${obj.fqn.name}`);\n }\n const report = testFramework.computeTestCoverage(files, fqns);\n const output =\n String(opts.format).toLowerCase() === 'json'\n ? testFramework.renderTestCoverageJson(report)\n : testFramework.renderTestCoverageMarkdown(report);\n if (opts.out) {\n const out = path.resolve(String(opts.out));\n await fs.mkdir(path.dirname(out), { recursive: true });\n await fs.writeFile(out, output, 'utf8');\n console.error(\n `Wrote ${out} — ${report.withTests}/${report.total} object(s) covered (${report.coveragePct}%).`,\n );\n } else {\n process.stdout.write(output + '\\n');\n }\n });\n\n return cmd;\n}\n\n/** Convert a simple glob pattern (`*` wildcard, `.` literal) to a RegExp. */\nfunction globToRegex(pattern: string): RegExp {\n const escaped = pattern.replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&').replace(/\\*/g, '.*');\n return new RegExp(`^${escaped}$`, 'i');\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { createConnection, DatabricksExecutor, getProfile } from '@ddt-tools/core';\n\n/**\n * `ddt branch` — PlanetScale-style branching for Databricks using\n * Unity Catalog **SHALLOW CLONE**. Unlike Snowflake's database-level\n * zero-copy clone, UC shallow-clone is per-table — so a \"branch\" is\n * a new schema containing shallow clones of every table in a base\n * schema.\n *\n * Subcommands:\n * create <name> --from <catalog.schema> [--connection <profile>]\n * drop <name> --catalog <catalog> [--connection <profile>]\n *\n * The MVP creates the destination schema and one SHALLOW CLONE per\n * source table; views, functions, and other UC objects are emitted\n * as commented-out scaffolds (manual port is needed because UC\n * doesn't shallow-clone non-table objects). The generated SQL is\n * emitted offline by default and executed when `--connection` is\n * supplied.\n */\nexport function branchCommand(): Command {\n const cmd = new Command('branch').description(\n 'PlanetScale-style branching for Databricks via UC SHALLOW CLONE. create / drop.',\n );\n\n cmd\n .command('create <name>')\n .description(\n 'Create a SHALLOW CLONE of every table in <catalog.schema> into a new branch schema named <name>.',\n )\n .requiredOption('--from <catalog.schema>', 'Base schema to clone, in catalog.schema form.')\n .option(\n '--connection <profile>',\n 'Connection profile to execute against. Omit to emit SQL only.',\n )\n .option(\n '-o, --out <path>',\n 'Write generated SQL to a file. Defaults to stdout when --connection is omitted.',\n )\n .action(async (name, opts) => {\n const branchSchema = String(name);\n const fromParts = String(opts.from).split('.');\n if (fromParts.length !== 2)\n throw new Error('--from must be in catalog.schema form (e.g. main.gold).');\n const [catalog, schema] = fromParts;\n const branchFqn = `${catalog}.${branchSchema}`;\n const sql: string[] = [];\n sql.push(`-- Branch ${branchFqn} = shallow clone of ${catalog}.${schema} (table-level).`);\n sql.push(`CREATE SCHEMA IF NOT EXISTS ${branchFqn};`);\n if (opts.connection) {\n // Live mode: list tables in source schema, emit clones.\n const profile = await getProfile(String(opts.connection));\n const conn = createConnection(profile);\n try {\n await conn.connect();\n const rows = await conn.query(`SHOW TABLES IN ${catalog}.${schema}`);\n for (const r of Array.isArray(rows) ? rows : []) {\n const rec = r as Record<string, unknown>;\n const t = String(rec.tableName ?? rec.name ?? '');\n if (!t) continue;\n sql.push(\n `CREATE OR REPLACE TABLE ${branchFqn}.${t} SHALLOW CLONE ${catalog}.${schema}.${t};`,\n );\n }\n const executor = new DatabricksExecutor(conn);\n for (const stmt of sql.filter((s) => !s.startsWith('--'))) {\n console.error(`> ${stmt.split('\\n')[0]}`);\n await executor.execute(stmt);\n }\n console.error('Done.');\n } finally {\n await conn.disconnect();\n }\n return;\n }\n // Offline mode: emit a SQL stub the user can fill in by listing\n // the source schema's tables and running this once-per-table.\n sql.push(\n `-- For each table in ${catalog}.${schema} (run \\`SHOW TABLES IN ${catalog}.${schema}\\` to enumerate):`,\n );\n sql.push(\n `-- CREATE OR REPLACE TABLE ${branchFqn}.<table> SHALLOW CLONE ${catalog}.${schema}.<table>;`,\n );\n sql.push('');\n const out = sql.join('\\n') + '\\n';\n if (opts.out) {\n const p = path.resolve(String(opts.out));\n await fs.mkdir(path.dirname(p), { recursive: true });\n await fs.writeFile(p, out, 'utf8');\n console.error(`Wrote ${p}.`);\n } else {\n process.stdout.write(out);\n }\n });\n\n cmd\n .command('drop <name>')\n .description('Drop a branch schema (CASCADE).')\n .requiredOption('--catalog <catalog>', 'Catalog the branch lives in.')\n .option('--connection <profile>', 'Connection profile. Omit to emit SQL only.')\n .option('-o, --out <path>', 'Write generated SQL to a file.')\n .action(async (name, opts) => {\n const sql = `-- Drop branch schema\\nDROP SCHEMA IF EXISTS ${opts.catalog}.${name} CASCADE;\\n`;\n if (opts.connection) {\n const profile = await getProfile(String(opts.connection));\n const conn = createConnection(profile);\n try {\n await conn.connect();\n const executor = new DatabricksExecutor(conn);\n await executor.execute(sql);\n console.error('Done.');\n } finally {\n await conn.disconnect();\n }\n return;\n }\n if (opts.out) {\n const p = path.resolve(String(opts.out));\n await fs.mkdir(path.dirname(p), { recursive: true });\n await fs.writeFile(p, sql, 'utf8');\n console.error(`Wrote ${p}.`);\n } else {\n process.stdout.write(sql);\n }\n });\n\n return cmd;\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport {\n interop,\n loadProject,\n pac,\n parseProjectModel,\n schema,\n validate as validateNs,\n type DatabricksObject,\n} from '@ddt-tools/core';\n\n/**\n * `ddt schema` — interop with third-party schema-modeling formats.\n * Mirrors `sdt schema`. See root NOTICE for the interop attribution\n * and the \"what this product is NOT\" statement.\n */\nexport function schemaCommand(): Command {\n const cmd = new Command('schema').description(\n 'Interop with third-party schema formats (DBML import/export; draw.io export). NOT a separate data modeler — DDT remains the canonical model.',\n );\n\n cmd\n .command('import-dbml <file>')\n .description('Import a DBML file and emit Databricks CREATE TABLE files.')\n .option('-o, --out <path>', 'Output directory. Default ./imported/.')\n .action(async (filePath, opts) => {\n const text = await fs.readFile(path.resolve(String(filePath)), 'utf8');\n const doc = schema.parseDbml(text);\n const out = opts.out ? path.resolve(String(opts.out)) : path.resolve('imported');\n await fs.mkdir(out, { recursive: true });\n let written = 0;\n for (const t of doc.tables) {\n const ddl = renderTableDdl(t, doc.refs);\n const dir = path.join(out, 'main', t.schema, 'tables');\n await fs.mkdir(dir, { recursive: true });\n const file = path.join(dir, `${t.name}.sql`);\n await fs.writeFile(file, ddl, 'utf8');\n written++;\n }\n console.error(`Imported ${written} table(s) from ${filePath} into ${out}.`);\n console.error(`Catalog defaulted to main; rename the top-level folder if needed.`);\n });\n\n cmd\n .command('export-dbml')\n .description(\n 'Emit DBML text from a project model. Lossy projection — UC-specific features become comments.',\n )\n .requiredOption('--source <path>', '.ddtproj or .ddtpac to export.')\n .option('-o, --out <path>', 'Output file. Defaults to stdout.')\n .action(async (opts) => {\n const model = await loadModel(String(opts.source));\n const text = schema.emitDbml(model);\n await emit(text, opts.out);\n });\n\n cmd\n .command('export-drawio')\n .description(\n 'Emit a draw.io / diagrams.net XML file from a project model. Open in any diagrams.net editor.',\n )\n .requiredOption('--source <path>', '.ddtproj or .ddtpac to export.')\n .option('-o, --out <path>', 'Output file. Defaults to ./schema.drawio.')\n .option('--columns <n>', 'Grid columns (used when --auto-layout is off). Default 4.', (v) =>\n parseInt(v, 10),\n )\n .option(\n '--auto-layout',\n 'Apply force-directed layout — connected tables cluster together. Default: alphabetical grid.',\n )\n .option(\n '--print',\n 'Print-friendly mode: monochrome palette, US Letter landscape page settings.',\n )\n .action(async (opts) => {\n const model = await loadModel(String(opts.source));\n const text = schema.emitDrawio(model, {\n ...(typeof opts.columns === 'number' ? { columns: opts.columns } : {}),\n ...(opts.autoLayout ? { autoLayout: true } : {}),\n ...(opts.print ? { print: true } : {}),\n });\n const outPath = opts.out ? path.resolve(String(opts.out)) : path.resolve('schema.drawio');\n await fs.mkdir(path.dirname(outPath), { recursive: true });\n await fs.writeFile(outPath, text, 'utf8');\n const flags =\n [opts.autoLayout && 'auto-layout', opts.print && 'print-mode'].filter(Boolean).join(', ') ||\n 'default';\n console.error(\n `Wrote ${outPath} (${text.length} bytes). Flags: ${flags}. Open in any draw.io / diagrams.net editor.`,\n );\n });\n\n // ─── Multi-format emitters ───\n for (const fmt of [\n {\n name: 'jsonschema',\n emit: interop.emitJsonSchema,\n ext: 'json',\n why: 'API contracts, NoSQL, payload validation.',\n },\n {\n name: 'avro',\n emit: interop.emitAvro,\n ext: 'avsc',\n why: 'Kafka / streaming pipelines with schema-registry.',\n },\n {\n name: 'protobuf',\n emit: interop.emitProtobuf,\n ext: 'proto',\n why: 'gRPC services, cross-language data contracts.',\n },\n {\n name: 'graphql',\n emit: interop.emitGraphqlSdl,\n ext: 'graphql',\n why: 'GraphQL APIs that expose the schema.',\n },\n {\n name: 'plantuml',\n emit: interop.emitPlantumlEr,\n ext: 'puml',\n why: 'Text-based ER diagrams (alternative to Mermaid).',\n },\n {\n name: 'typescript',\n emit: interop.emitTypescript,\n ext: 'ts',\n why: 'Generate TypeScript interfaces for app code.',\n },\n {\n name: 'pydantic',\n emit: interop.emitPydantic,\n ext: 'py',\n why: 'Generate Pydantic models for Python apps.',\n },\n { name: 'java', emit: interop.emitJavaDto, ext: 'java', why: 'Generate Java record DTOs.' },\n {\n name: 'markdown',\n emit: interop.emitMarkdownDocs,\n ext: 'md',\n why: 'Schema docs rendered by GitHub / GitLab.',\n },\n {\n name: 'html',\n emit: interop.emitHtmlDocs,\n ext: 'html',\n why: 'Self-contained schema-docs page for distribution.',\n },\n ]) {\n cmd\n .command(`export-${fmt.name}`)\n .description(`Emit ${fmt.name.toUpperCase()} from the project model. Use: ${fmt.why}`)\n .requiredOption('--source <path>', '.ddtproj or .ddtpac to export.')\n .option('-o, --out <path>', `Output file. Defaults to ./schema.${fmt.ext}.`)\n .action(async (opts) => {\n const model = await loadModel(String(opts.source));\n const text = fmt.emit(model);\n const outPath = opts.out\n ? path.resolve(String(opts.out))\n : path.resolve(`schema.${fmt.ext}`);\n await fs.mkdir(path.dirname(outPath), { recursive: true });\n await fs.writeFile(outPath, text, 'utf8');\n console.error(`Wrote ${outPath} (${text.length} bytes).`);\n });\n }\n\n // ─── Star-schema validator ───\n cmd\n .command('validate-star')\n .description(\n 'Validate a star schema rooted at a fact table. Classifies each connected dim by SCD type, reports FK coverage + naming issues.',\n )\n .requiredOption('--source <path>', '.ddtproj or .ddtpac containing the star.')\n .requiredOption('--root <fqn>', 'Fully-qualified fact-table FQN (catalog.schema.fact_name).')\n .option('--format <fmt>', 'table | json | markdown. Default table.', 'table')\n .option('-o, --out <path>', 'Output file. Defaults to stdout.')\n .action(async (opts) => {\n const model = await loadModel(String(opts.source));\n const report = validateNs.validateStar(model, String(opts.root), {\n source: String(opts.source),\n });\n\n const fmt = String(opts.format ?? 'table').toLowerCase();\n let payload: string;\n if (fmt === 'json') {\n payload = JSON.stringify(report, null, 2);\n } else if (fmt === 'markdown') {\n payload = renderStarMarkdown(report);\n } else if (fmt === 'table') {\n payload = validateNs.formatStarReport(report);\n } else {\n throw new Error(`Unknown --format: ${fmt}. Use table | json | markdown.`);\n }\n await emit(payload, opts.out);\n\n if (!report.factExists || report.issues.length > 0) {\n process.exitCode = 1;\n }\n });\n\n // ─── Snowflake-schema refactor proposer ───\n cmd\n .command('suggest-snowflake-schema')\n .description(\n 'Propose snowflake-schema refactors: detect column groups on star dims that look like candidates for extraction (geography, category, org).',\n )\n .requiredOption('--source <path>', '.ddtproj or .ddtpac containing the star.')\n .requiredOption('--root <fqn>', 'Fully-qualified fact-table FQN (catalog.schema.fact_name).')\n .option('--format <fmt>', 'table | json | markdown. Default table.', 'table')\n .option('-o, --out <path>', 'Output file. Defaults to stdout.')\n .action(async (opts) => {\n const model = await loadModel(String(opts.source));\n const proposal = validateNs.proposeSnowflakeSchema(model, String(opts.root), {\n source: String(opts.source),\n });\n\n const fmt = String(opts.format ?? 'table').toLowerCase();\n let payload: string;\n if (fmt === 'json') {\n payload = JSON.stringify(proposal, null, 2);\n } else if (fmt === 'markdown') {\n payload = renderSnowflakeSchemaMarkdown(proposal);\n } else if (fmt === 'table') {\n payload = validateNs.formatSnowflakeSchemaProposal(proposal);\n } else {\n throw new Error(`Unknown --format: ${fmt}. Use table | json | markdown.`);\n }\n await emit(payload, opts.out);\n });\n\n // ─── Sample-data → CREATE TABLE inference ───\n cmd\n .command('infer-csv <file>')\n .description(\n 'Read a CSV sample and emit a Databricks CREATE TABLE with heuristic type inference. Review before deploy.',\n )\n .requiredOption(\n '--name <fqn>',\n 'Fully-qualified table name (catalog.schema.table or schema.table).',\n )\n .option('--delimiter <char>', 'CSV delimiter. Default: comma.', ',')\n .option(\n '--no-header',\n 'Treat the first row as data, not header. Generated column names: column_1, column_2, …',\n )\n .option('--max-sample-rows <n>', 'Cap on rows sampled. Default 1000.', (v) => parseInt(v, 10))\n .option(\n '--or-replace',\n 'Emit CREATE OR REPLACE TABLE instead of CREATE TABLE IF NOT EXISTS.',\n false,\n )\n .option(\n '--using <format>',\n 'Storage format (DELTA / PARQUET / CSV / JSON / ICEBERG). Default DELTA.',\n 'DELTA',\n )\n .option('-o, --out <path>', 'Output file. Defaults to stdout.')\n .action(async (filePath, opts) => {\n const text = await fs.readFile(path.resolve(String(filePath)), 'utf8');\n const inferred = schema.inferSchemaFromCsv(\n text,\n {\n delimiter: String(opts.delimiter),\n hasHeader: opts.header !== false,\n ...(typeof opts.maxSampleRows === 'number' ? { maxSampleRows: opts.maxSampleRows } : {}),\n },\n path.basename(String(filePath)),\n );\n const parts = String(opts.name).split('.').filter(Boolean);\n const fqn =\n parts.length === 3\n ? { database: parts[0]!, schema: parts[1]!, name: parts[2]! }\n : parts.length === 2\n ? { schema: parts[0]!, name: parts[1]! }\n : { name: parts[0] ?? 'inferred_table' };\n const ddl = schema.renderCreateTable(inferred, {\n fqn,\n orReplace: !!opts.orReplace,\n using: String(opts.using),\n });\n await emit(ddl, opts.out);\n console.error(\n `Sampled ${inferred.sampleRowCount} row(s); inferred ${inferred.columns.length} column(s).`,\n );\n const allNull = inferred.columns.filter((c) => c.allNull);\n if (allNull.length > 0) {\n console.error(\n `Warning: ${allNull.length} column(s) had no values in the sample — types defaulted to STRING. Review the generated DDL.`,\n );\n }\n });\n\n cmd\n .command('infer-parquet <file>')\n .description(\n \"Read a Parquet file's metadata footer and emit a Databricks CREATE TABLE. No data is read — only the schema header.\",\n )\n .requiredOption(\n '--name <fqn>',\n 'Fully-qualified table name (catalog.schema.table or schema.table).',\n )\n .option(\n '--or-replace',\n 'Emit CREATE OR REPLACE TABLE instead of CREATE TABLE IF NOT EXISTS.',\n false,\n )\n .option(\n '--using <format>',\n 'Storage format (DELTA / PARQUET / ICEBERG / ...). Default DELTA.',\n 'DELTA',\n )\n .option('-o, --out <path>', 'Output file. Defaults to stdout.')\n .action(async (filePath, opts) => {\n const buf = await fs.readFile(path.resolve(String(filePath)));\n const inferred = await schema.inferSchemaFromParquet(buf, path.basename(String(filePath)));\n const parts = String(opts.name).split('.').filter(Boolean);\n const fqn =\n parts.length === 3\n ? { database: parts[0]!, schema: parts[1]!, name: parts[2]! }\n : parts.length === 2\n ? { schema: parts[0]!, name: parts[1]! }\n : { name: parts[0] ?? 'inferred_table' };\n const ddl = schema.renderCreateTable(inferred, {\n fqn,\n orReplace: !!opts.orReplace,\n using: String(opts.using),\n });\n await emit(ddl, opts.out);\n console.error(\n `Parquet schema: ${inferred.columns.length} column(s); reported ${inferred.sampleRowCount} row(s) in metadata.`,\n );\n });\n\n // ─── Multi-format importers ───\n cmd\n .command('import-ddl <file>')\n .description(\n 'Universal DDL importer — parse any CREATE TABLE statements (erwin / ER/Studio / PowerDesigner / DbSchema / Hackolade / Visio / DataGrip all \"Forward Engineer to Script\"; we read it).',\n )\n .option('-o, --out <path>', 'Output directory. Default ./imported/.')\n .action(async (filePath, opts) => {\n const text = await fs.readFile(path.resolve(String(filePath)), 'utf8');\n const result = interop.parseUniversalDdl(text);\n await writeImportedTables(\n result,\n opts.out ? path.resolve(String(opts.out)) : path.resolve('imported'),\n );\n });\n\n cmd\n .command('import-jsonschema <file>')\n .description('Import a JSON Schema document; each top-level object schema becomes a table.')\n .option('-o, --out <path>', 'Output directory. Default ./imported/.')\n .action(async (filePath, opts) => {\n const text = await fs.readFile(path.resolve(String(filePath)), 'utf8');\n const result = interop.parseJsonSchema(text);\n await writeImportedTables(\n result,\n opts.out ? path.resolve(String(opts.out)) : path.resolve('imported'),\n );\n });\n\n cmd\n .command('import-dbt <file>')\n .description('Import a dbt-generated manifest.json; each model/seed/source becomes a table.')\n .option('-o, --out <path>', 'Output directory. Default ./imported/.')\n .action(async (filePath, opts) => {\n const text = await fs.readFile(path.resolve(String(filePath)), 'utf8');\n const result = interop.parseDbtManifest(text);\n await writeImportedTables(\n result,\n opts.out ? path.resolve(String(opts.out)) : path.resolve('imported'),\n );\n });\n\n return cmd;\n}\n\nasync function writeImportedTables(result: interop.ImportResult, outDir: string): Promise<void> {\n await fs.mkdir(outDir, { recursive: true });\n let written = 0;\n for (const t of result.tables) {\n const catalog = t.database ?? 'main';\n const sch = t.schema ?? 'default';\n const dir = path.join(outDir, catalog, sch, 'tables');\n await fs.mkdir(dir, { recursive: true });\n const file = path.join(dir, `${t.name}.sql`);\n const colDdl = t.columns\n .map((c) => {\n const mods: string[] = [];\n if (c.nullable === false) mods.push('NOT NULL');\n if (c.default) mods.push(`DEFAULT ${c.default}`);\n return ` ${c.name.padEnd(28)} ${databricksType(c.dataType)}${mods.length > 0 ? ' ' + mods.join(' ') : ''}${c.comment ? ` COMMENT '${c.comment.replace(/'/g, \"''\")}'` : ''}`;\n })\n .join(',\\n');\n const ddl = `-- Imported by \\`ddt schema import-*\\` from source: ${result.source}.\\n-- Review and refine; DDT is the canonical model from here on.\\n\\nCREATE OR REPLACE TABLE ${catalog}.${sch}.${t.name} (\\n${colDdl}\\n)\\nUSING DELTA\\nTBLPROPERTIES ('delta.enableDeletionVectors' = 'true')${t.comment ? `\\nCOMMENT '${t.comment.replace(/'/g, \"''\")}'` : ''};\\n`;\n await fs.writeFile(file, ddl, 'utf8');\n written++;\n }\n console.error(`Imported ${written} table(s) into ${outDir}.`);\n if (result.warnings.length > 0) {\n console.error('Warnings (review before deploy):');\n for (const w of result.warnings) console.error(` - ${w}`);\n }\n}\n\nfunction databricksType(dbmlType: string): string {\n const t = dbmlType.toLowerCase().trim();\n if (t === 'int' || t === 'integer' || t === 'serial') return 'INT';\n if (t === 'bigint' || t.startsWith('number')) return 'BIGINT';\n if (t === 'smallint') return 'SMALLINT';\n if (t === 'decimal' || t === 'numeric') return 'DECIMAL(38,9)';\n if (t === 'float' || t === 'double') return 'DOUBLE';\n if (t === 'boolean' || t === 'bool') return 'BOOLEAN';\n if (t === 'date') return 'DATE';\n if (t === 'datetime' || t === 'timestamp' || t === 'timestamp_ntz') return 'TIMESTAMP';\n if (t === 'text' || t === 'string' || t.startsWith('varchar')) return 'STRING';\n if (t === 'variant' || t === 'json' || t === 'jsonb') return 'MAP<STRING, STRING>';\n if (t === 'array') return 'ARRAY<STRING>';\n if (t === 'uuid') return 'STRING';\n return dbmlType.toUpperCase();\n}\n\nfunction renderTableDdl(t: schema.DbmlTable, refs: readonly schema.DbmlRef[]): string {\n const lines: string[] = [];\n lines.push(`-- Imported from DBML by \\`ddt schema import-dbml\\`.`);\n lines.push(`-- Review and refine; DDT is the canonical model from here on.`);\n if (t.note) lines.push(`-- ${t.note}`);\n lines.push('');\n const colDdl = t.columns.map((c) => {\n const mods: string[] = [];\n if (c.notNull) mods.push('NOT NULL');\n if (c.default) mods.push(`DEFAULT ${c.default}`);\n return ` ${c.name.padEnd(28)} ${databricksType(c.type)}${mods.length > 0 ? ' ' + mods.join(' ') : ''}${c.note ? ` COMMENT '${c.note.replace(/'/g, \"''\")}'` : ''}`;\n });\n const tableRefs = refs.filter((r) =>\n r.from.toLowerCase().startsWith(`${t.schema.toLowerCase()}.${t.name.toLowerCase()}.`),\n );\n if (tableRefs.length > 0) {\n lines.push(`-- Inferred references (UC doesn't enforce FKs; this is metadata only):`);\n for (const r of tableRefs) lines.push(`-- ${r.from} ${r.cardinality} ${r.to}`);\n lines.push('');\n }\n lines.push(`CREATE OR REPLACE TABLE main.${t.schema}.${t.name} (`);\n lines.push(colDdl.join(',\\n'));\n lines.push(')');\n lines.push(`USING DELTA`);\n lines.push(`TBLPROPERTIES ('delta.enableDeletionVectors' = 'true')`);\n if (t.note) lines.push(`COMMENT '${t.note.replace(/'/g, \"''\")}'`);\n lines.push(';\\n');\n return lines.join('\\n');\n}\n\nfunction renderSnowflakeSchemaMarkdown(p: validateNs.SnowflakeSchemaProposal): string {\n const lines: string[] = [];\n lines.push(`# Snowflake-schema refactor proposal — \\`${p.fact}\\``);\n lines.push('');\n lines.push(`Generated: ${p.generatedAt}`);\n if (p.source) lines.push(`Source: \\`${p.source}\\``);\n lines.push('');\n if (!p.factExists) {\n lines.push(`**Fact not found in the project.**`);\n return lines.join('\\n');\n }\n if (p.dims.length === 0) {\n lines.push('_No refactor candidates detected._');\n return lines.join('\\n');\n }\n for (const d of p.dims) {\n lines.push(`## \\`${d.dim}\\` (${d.scdType})`);\n lines.push('');\n for (const g of d.groups) {\n lines.push(`### ${g.kind} — columns: \\`${g.columns.join('`, `')}\\``);\n lines.push('');\n if (g.proposedDim) {\n lines.push(`**Proposal:** extract to \\`${g.proposedDim}\\`.`);\n } else {\n lines.push(`**Proposal:** keep on parent dim (audit metadata).`);\n }\n lines.push('');\n lines.push(`*Why:* ${g.reasoning}`);\n lines.push('');\n }\n }\n return lines.join('\\n');\n}\n\nfunction renderStarMarkdown(report: validateNs.StarValidationReport): string {\n const lines: string[] = [];\n lines.push(`# Star validation — \\`${report.fact}\\``);\n lines.push('');\n lines.push(`Generated: ${report.generatedAt}`);\n if (report.source) lines.push(`Source: \\`${report.source}\\``);\n lines.push('');\n if (!report.factExists) {\n lines.push(`**${report.issues[0]}**`);\n return lines.join('\\n');\n }\n lines.push(\n `**Fan-out:** ${report.fanOut} · **CLUSTER BY:** ${report.clusterBy.length > 0 ? report.clusterBy.join(', ') : '_none_'}`,\n );\n lines.push('');\n if (report.dimensions.length > 0) {\n lines.push('## Dimensions');\n lines.push('');\n lines.push('| Dim | SCD Type | Business Key | Notes |');\n lines.push('| --- | --- | --- | --- |');\n for (const d of report.dimensions) {\n lines.push(\n `| \\`${d.fqn}\\` | ${d.scdType} | ${d.bk ? `\\`${d.bk}\\`` : '_none_'} | ${d.reasons.join('; ')} |`,\n );\n }\n lines.push('');\n }\n if (report.issues.length > 0) {\n lines.push('## Issues');\n lines.push('');\n for (const i of report.issues) lines.push(`- ⚠️ ${i}`);\n }\n return lines.join('\\n');\n}\n\nasync function loadModel(sourcePath: string): Promise<DatabricksObject[]> {\n if (sourcePath.endsWith('.ddtpac')) {\n const c = await pac.readPac(sourcePath);\n return c.model;\n }\n const loaded = await loadProject(sourcePath);\n return await parseProjectModel(loaded);\n}\n\nasync function emit(text: string, out: unknown): Promise<void> {\n if (out) {\n const p = path.resolve(String(out));\n await fs.mkdir(path.dirname(p), { recursive: true });\n await fs.writeFile(p, text + (text.endsWith('\\n') ? '' : '\\n'), 'utf8');\n console.error(`Wrote ${p}.`);\n } else {\n process.stdout.write(text + (text.endsWith('\\n') ? '' : '\\n'));\n }\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport {\n loadProject,\n pac,\n parseProjectModel,\n schema,\n type DatabricksObject,\n} from '@ddt-tools/core';\n\n/**\n * `ddt suggest` — propose FK / PK / UK / composite-PK candidates\n * with reasoning. Mirrors `sdt suggest`.\n */\nexport function suggestCommand(): Command {\n const cmd = new Command('suggest');\n cmd\n .description(\n 'Suggest FK / PK / UK / composite-PK candidates with reasoning. Output is Markdown by default.',\n )\n .requiredOption('--source <path>', '.ddtproj or .ddtpac to analyze.')\n .option('--format <fmt>', 'markdown | json. Default markdown.', 'markdown')\n .option('-o, --out <path>', 'Output file. Defaults to stdout.')\n .action(async (opts) => {\n const model = await loadModel(String(opts.source));\n const report = schema.suggestForModel(model);\n const fmt = String(opts.format ?? 'markdown').toLowerCase();\n const text =\n fmt === 'json' ? JSON.stringify(report, null, 2) : schema.formatSuggestionReport(report);\n if (opts.out) {\n const p = path.resolve(String(opts.out));\n await fs.mkdir(path.dirname(p), { recursive: true });\n await fs.writeFile(p, text + (text.endsWith('\\n') ? '' : '\\n'), 'utf8');\n console.error(`Wrote ${p} (${report.totalSuggestions} suggestion(s)).`);\n } else {\n process.stdout.write(text + (text.endsWith('\\n') ? '' : '\\n'));\n }\n });\n return cmd;\n}\n\nasync function loadModel(sourcePath: string): Promise<DatabricksObject[]> {\n if (sourcePath.endsWith('.ddtpac')) {\n const c = await pac.readPac(sourcePath);\n return c.model;\n }\n const loaded = await loadProject(sourcePath);\n return await parseProjectModel(loaded);\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { createConnection, getProfile, queryHistory } from '@ddt-tools/core';\n\ntype QueryHistoryEntry = queryHistory.QueryHistoryEntry;\n\n/**\n * `ddt history` — two modes.\n *\n * 1. **Manifest mode** (default) — read deploy manifests from a\n * directory and show a chronological summary.\n *\n * 2. **Live mode** (triggered by `--last`, `--query`, or `--verify`)\n * — query the workspace `system.query.*` tables via the\n * DatabricksQueryHistoryReader. Requires `--connection <profile>`.\n *\n * Mirrors `sdt history`.\n */\ninterface Manifest {\n version: 1;\n deployedAt?: string;\n workspaceHost?: string;\n finalState?: string;\n failedStepId?: string | null;\n steps?: Array<{\n status?: string;\n objectType?: string;\n fqn?: string;\n forwardSql?: string;\n reverseSql?: string;\n }>;\n}\n\nexport function historyCommand(): Command {\n const cmd = new Command('history');\n cmd\n .description(\n 'List deploy manifests (default) or query live system.query.* via --last/--query/--verify.',\n )\n .option(\n '--dir <path>',\n 'Directory containing *.json manifests (manifest mode).',\n './.ddt/history',\n )\n .option('--limit <n>', 'Manifest mode: most-recent N entries. Live mode: max rows.', '20')\n .option('--json', 'Emit JSON instead of human-readable table.', false)\n .option(\n '--full-sql',\n 'Include full SQL text in the output (default truncated to 120 chars).',\n false,\n )\n .option(\n '--connection <profile>',\n 'Connection profile (required for --last / --query / --verify).',\n )\n .option('--last [n]', 'Live mode: show the N most-recent queries. Default 20.')\n .option('--query <id>', 'Live mode: look up a single query by its statement_id.')\n .option(\n '--verify <tag>',\n 'Live mode: read all queries tagged with this string. Use the `DDT-TAG` auto-tag from `ddt publish --apply`.',\n )\n .option('--since <iso>', 'Live mode: only include entries after this ISO 8601 timestamp.')\n .action(\n async (opts: {\n dir?: string;\n limit?: string;\n json?: boolean;\n fullSql?: boolean;\n connection?: string;\n last?: boolean | string;\n query?: string;\n verify?: string;\n since?: string;\n }) => {\n const isLive =\n opts.last !== undefined || opts.query !== undefined || opts.verify !== undefined;\n if (isLive) await runLive(opts);\n else await runManifests(opts);\n },\n );\n return cmd;\n}\n\nasync function runManifests(opts: {\n dir?: string;\n limit?: string;\n json?: boolean;\n fullSql?: boolean;\n}): Promise<void> {\n const dir = path.resolve(String(opts.dir ?? './.ddt/history'));\n let files: string[];\n try {\n const entries = await fs.readdir(dir);\n files = entries.filter((f) => f.endsWith('.json')).map((f) => path.join(dir, f));\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n console.error(\n `No history directory at ${dir}. Pass --dir <path> or pipe deploys to write manifests there.`,\n );\n process.exitCode = 1;\n return;\n }\n throw err;\n }\n\n const entries: Array<{ path: string; mtime: Date; manifest: Manifest }> = [];\n for (const f of files) {\n try {\n const raw = await fs.readFile(f, 'utf8');\n const m = JSON.parse(raw) as Manifest;\n const stat = await fs.stat(f);\n entries.push({ path: f, mtime: stat.mtime, manifest: m });\n } catch {\n // skip files that don't parse\n }\n }\n entries.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());\n\n const limit = parseInt(String(opts.limit ?? 20), 10);\n const visible = entries.slice(0, limit > 0 ? limit : entries.length);\n\n if (opts.json) {\n console.log(\n JSON.stringify(\n visible.map((e) => ({ path: e.path, mtime: e.mtime.toISOString(), ...e.manifest })),\n null,\n 2,\n ),\n );\n return;\n }\n\n if (visible.length === 0) {\n console.log(`No manifests found in ${dir}.`);\n return;\n }\n console.log(`History: ${visible.length} of ${entries.length} deploys at ${dir}`);\n console.log('');\n console.log(\n ' DEPLOYED AT WORKSPACE FINAL STATE STEPS',\n );\n console.log(\n ' ─────────────────── ────────────────────────────────── ────────────────── ─────',\n );\n for (const e of visible) {\n const m = e.manifest;\n const when = m.deployedAt\n ? new Date(m.deployedAt).toISOString().slice(0, 19).replace('T', ' ')\n : e.mtime.toISOString().slice(0, 19).replace('T', ' ');\n const host = (m.workspaceHost ?? '?').padEnd(34).slice(0, 34);\n const state = (m.finalState ?? '?').padEnd(18).slice(0, 18);\n const succ = m.steps?.filter((s) => s.status === 'SUCCESS').length ?? 0;\n const tot = m.steps?.length ?? 0;\n console.log(` ${when} ${host} ${state} ${succ}/${tot}`);\n if (opts.fullSql) {\n for (const s of m.steps ?? []) {\n if (s.forwardSql) console.log(` [forward] ${s.fqn ?? ''}\\n${indent(s.forwardSql, 8)}`);\n }\n }\n }\n console.log('');\n console.log(\n `Pass --json for machine-readable output, --limit <n> to control depth, --full-sql to expand each step.`,\n );\n}\n\nasync function runLive(opts: {\n connection?: string;\n last?: boolean | string;\n query?: string;\n verify?: string;\n since?: string;\n limit?: string;\n json?: boolean;\n fullSql?: boolean;\n}): Promise<void> {\n if (!opts.connection) {\n console.error('Live history mode requires --connection <profile>.');\n process.exitCode = 1;\n return;\n }\n const profile = await getProfile(String(opts.connection));\n const conn = createConnection(profile);\n await conn.connect();\n try {\n const reader = new queryHistory.DatabricksQueryHistoryReader(conn);\n const limit = Math.max(1, parseInt(String(opts.limit ?? '20'), 10) || 20);\n const since = opts.since ? new Date(opts.since) : undefined;\n\n let entries: QueryHistoryEntry[] = [];\n if (opts.query) {\n const e = await reader.readById(String(opts.query));\n entries = e ? [e] : [];\n } else if (opts.verify) {\n entries = await reader.readByTag(String(opts.verify), {\n ...(since ? { since } : {}),\n limit,\n });\n } else {\n const n = typeof opts.last === 'string' ? parseInt(opts.last, 10) || limit : limit;\n const user =\n (profile.auth as { user?: string; principalEmail?: string }).user ??\n (profile.auth as { principalEmail?: string }).principalEmail ??\n '';\n entries = await reader.readByUser(user, {\n ...(since ? { since } : {}),\n limit: n,\n });\n }\n\n if (opts.json) {\n process.stdout.write(JSON.stringify(entries, null, 2) + '\\n');\n return;\n }\n renderEntries(entries, Boolean(opts.fullSql));\n } finally {\n await conn.disconnect();\n }\n}\n\nfunction renderEntries(entries: readonly QueryHistoryEntry[], fullSql: boolean): void {\n if (entries.length === 0) {\n console.log('No matching queries found.');\n return;\n }\n console.log(`${entries.length} quer${entries.length === 1 ? 'y' : 'ies'}:`);\n console.log('');\n console.log(' STARTED STATUS DURATION USER STATEMENT_ID');\n console.log(\n ' ─────────────────── ──────── ──────── ───────────────────── ────────────────────────────',\n );\n for (const e of entries) {\n const when = e.startedAt.slice(0, 19).replace('T', ' ');\n const status = e.status.toUpperCase().padEnd(8);\n const dur = `${e.durationMs}ms`.padEnd(8);\n const user = (e.user ?? '?').padEnd(20).slice(0, 20);\n console.log(` ${when} ${status} ${dur} ${user} ${e.queryId}`);\n const sql = fullSql ? e.sqlText : truncate(e.sqlText, 120);\n if (sql)\n console.log(\n ` ${sql\n .split('\\n')\n .map((l: string) => l.trim())\n .filter(Boolean)\n .join(' ')}`,\n );\n if (e.queryTag) console.log(` tag: ${e.queryTag}`);\n if (e.errorMessage) console.log(` ERROR: ${e.errorMessage}`);\n }\n}\n\nfunction indent(text: string, n: number): string {\n const pad = ' '.repeat(n);\n return text\n .split('\\n')\n .map((l) => pad + l)\n .join('\\n');\n}\n\nfunction truncate(s: string, max: number): string {\n if (!s) return '';\n const collapsed = s.replace(/\\s+/g, ' ').trim();\n if (collapsed.length <= max) return collapsed;\n return collapsed.slice(0, max - 1) + '…';\n}\n","/**\n * `ddt audit-log emit` — export deploy + compare history records to\n * enterprise audit sinks. Reads `.ddt/history/*.json` (deploys) and\n * `.ddt/history/compare/*.json` (compares, AUDITCMP.1), normalises each\n * record via `@ddt-tools/core/auditLog.toAuditEvents`, then writes / POSTs\n * based on the `--sink` selector.\n */\nimport { Command } from 'commander';\nimport { writeFile } from 'node:fs/promises';\nimport { auditLog, loadCompareHistory, loadDeployHistory } from '@ddt-tools/core';\n\ntype Sink = 'file' | 'syslog' | 'splunk' | 'datadog' | 'otlp';\n\nexport function auditLogCommand(): Command {\n const cmd = new Command('audit-log');\n cmd.description(\n 'Export deploy history to enterprise audit sinks (file / syslog / Splunk HEC / Datadog Logs).',\n );\n\n cmd\n .command('emit')\n .description(\n 'Read .ddt/history/*.json (deploys) + .ddt/history/compare/*.json (compares) and emit records to the chosen sink. ' +\n '`--sink file|syslog` emit lines; `--sink splunk|datadog` POST HTTP.',\n )\n .requiredOption('--sink <kind>', \"One of: 'file' | 'syslog' | 'splunk' | 'datadog' | 'otlp'.\")\n .option(\n '--workspace <path>',\n 'Workspace root containing .ddt/history. Default cwd.',\n process.cwd(),\n )\n .option('-o, --out <path>', 'Output path (file/syslog sinks). Default stdout.')\n .option('--splunk-url <url>', 'Splunk HEC endpoint URL (splunk sink).')\n .option('--splunk-token <tok>', 'Splunk HEC token (splunk sink).')\n .option('--splunk-index <idx>', 'Splunk index (optional).')\n .option('--splunk-source <src>', 'Splunk source field (default: ddt).')\n .option('--datadog-site <site>', \"Datadog site (e.g. 'datadoghq.com').\")\n .option('--datadog-api-key <key>', 'Datadog API key.')\n .option('--datadog-tags <tags>', 'Datadog ddtags string (e.g. env:prod,team:data).')\n .option('--datadog-hostname <h>', 'Datadog hostname attribute.')\n .option('--syslog-host <h>', 'Syslog hostname field (default: localhost).')\n .option('--syslog-app <name>', 'Syslog app-name field (default: ddt).')\n .option('--syslog-facility <n>', 'Syslog facility (0-23, default 1).')\n .option('--otlp-url <url>', 'OTLP/HTTP logs endpoint, e.g. https://otelcol.example/v1/logs.')\n .option(\n '--otlp-header <kv...>',\n 'OTLP extra header (repeatable), e.g. --otlp-header authorization=Bearer\\\\ <tok>.',\n )\n .option('--otlp-service-name <name>', \"OTLP resource service.name (default: 'ddt').\")\n .option('--otlp-service-version <v>', 'OTLP resource service.version.')\n .option(\n '--dry-run',\n 'For splunk/datadog sinks, print the prepared HTTP request without POSTing.',\n false,\n )\n .action(async (opts: SinkOptions) => {\n const records = await loadDeployHistory(opts.workspace);\n const compareRecords = await loadCompareHistory(opts.workspace);\n const events = auditLog.toAuditEvents(records, compareRecords);\n if (events.length === 0) {\n process.stderr.write(\n `No deploy-history records (or compare-history records) found under ${opts.workspace}/.ddt/history\\n`,\n );\n return;\n }\n switch (opts.sink) {\n case 'file': {\n const lines = events.map((e) => auditLog.formatJsonLine(e)).join('');\n await emitLines(lines, opts.out);\n process.stderr.write(`Emitted ${events.length} JSONL audit record(s).\\n`);\n return;\n }\n case 'syslog': {\n const facility =\n opts.syslogFacility !== undefined ? Number(opts.syslogFacility) : undefined;\n const syslogOpts: auditLog.SyslogFormatOptions = {\n ...(opts.syslogHost !== undefined ? { hostname: opts.syslogHost } : {}),\n ...(opts.syslogApp !== undefined ? { appName: opts.syslogApp } : {}),\n ...(facility !== undefined && Number.isFinite(facility) ? { facility } : {}),\n };\n const lines =\n events.map((e) => auditLog.formatSyslogLine(e, syslogOpts)).join('\\n') + '\\n';\n await emitLines(lines, opts.out);\n process.stderr.write(`Emitted ${events.length} RFC 5424 syslog line(s).\\n`);\n return;\n }\n case 'splunk': {\n if (!opts.splunkUrl || !opts.splunkToken) {\n throw new Error('--sink splunk requires both --splunk-url and --splunk-token.');\n }\n const req = auditLog.buildSplunkHecRequest(events, {\n url: opts.splunkUrl,\n token: opts.splunkToken,\n ...(opts.splunkIndex !== undefined ? { index: opts.splunkIndex } : {}),\n ...(opts.splunkSource !== undefined ? { source: opts.splunkSource } : {}),\n });\n if (opts.dryRun) {\n await emitLines(formatRequestPreview(req), opts.out);\n } else {\n await postRequest(req);\n process.stderr.write(`Posted ${events.length} audit record(s) to Splunk HEC.\\n`);\n }\n return;\n }\n case 'otlp': {\n if (!opts.otlpUrl) {\n throw new Error('--sink otlp requires --otlp-url.');\n }\n const headerEntries = parseOtlpHeaders(opts.otlpHeader);\n const otlpOpts: auditLog.OtlpLogsOptions = {\n url: opts.otlpUrl,\n ...(Object.keys(headerEntries).length > 0 ? { headers: headerEntries } : {}),\n ...(opts.otlpServiceName !== undefined ? { serviceName: opts.otlpServiceName } : {}),\n ...(opts.otlpServiceVersion !== undefined\n ? { serviceVersion: opts.otlpServiceVersion }\n : {}),\n };\n const req = auditLog.buildOtlpLogsRequest(events, otlpOpts);\n if (opts.dryRun) {\n await emitLines(formatRequestPreview(req), opts.out);\n } else {\n await postRequest(req);\n process.stderr.write(`Posted ${events.length} audit record(s) to OTLP.\\n`);\n }\n return;\n }\n case 'datadog': {\n if (!opts.datadogSite || !opts.datadogApiKey) {\n throw new Error('--sink datadog requires both --datadog-site and --datadog-api-key.');\n }\n const req = auditLog.buildDatadogLogsRequest(events, {\n site: opts.datadogSite,\n apiKey: opts.datadogApiKey,\n ...(opts.datadogTags !== undefined ? { ddtags: opts.datadogTags } : {}),\n ...(opts.datadogHostname !== undefined ? { hostname: opts.datadogHostname } : {}),\n });\n if (opts.dryRun) {\n await emitLines(formatRequestPreview(req), opts.out);\n } else {\n await postRequest(req);\n process.stderr.write(`Posted ${events.length} audit record(s) to Datadog Logs.\\n`);\n }\n return;\n }\n default:\n throw new Error(`Unknown --sink value: ${String((opts as { sink: string }).sink)}.`);\n }\n });\n\n return cmd;\n}\n\ninterface SinkOptions {\n sink: Sink;\n workspace: string;\n out?: string;\n splunkUrl?: string;\n splunkToken?: string;\n splunkIndex?: string;\n splunkSource?: string;\n datadogSite?: string;\n datadogApiKey?: string;\n datadogTags?: string;\n datadogHostname?: string;\n syslogHost?: string;\n syslogApp?: string;\n syslogFacility?: string;\n otlpUrl?: string;\n otlpHeader?: string[];\n otlpServiceName?: string;\n otlpServiceVersion?: string;\n dryRun: boolean;\n}\n\nfunction parseOtlpHeaders(raw: string[] | undefined): Record<string, string> {\n const out: Record<string, string> = {};\n if (!raw) return out;\n for (const entry of raw) {\n const eq = entry.indexOf('=');\n if (eq <= 0) {\n throw new Error(`--otlp-header expects key=value, got: ${entry}`);\n }\n out[entry.slice(0, eq)] = entry.slice(eq + 1);\n }\n return out;\n}\n\nasync function emitLines(body: string, out?: string): Promise<void> {\n if (out) {\n await writeFile(out, body, 'utf8');\n } else {\n process.stdout.write(body);\n }\n}\n\nfunction formatRequestPreview(req: auditLog.HttpSinkRequest): string {\n const headers = Object.entries(req.headers)\n .map(([k, v]) => `${k}: ${v}`)\n .join('\\n');\n return `${req.method} ${req.url}\\n${headers}\\n\\n${req.body}\\n`;\n}\n\nasync function postRequest(req: auditLog.HttpSinkRequest): Promise<void> {\n const res = await fetch(req.url, { method: req.method, headers: req.headers, body: req.body });\n if (!res.ok) {\n const text = await res.text();\n throw new Error(`Audit sink POST failed: ${res.status} ${res.statusText} ${text}`);\n }\n}\n","import { promises as fs } from 'node:fs';\nimport { existsSync } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\n\n/**\n * `ddt install-hooks` — install a git pre-commit hook that runs\n * `ddt format --check` + `ddt validate` before allowing a commit.\n *\n * Husky-style: writes a single shell script to `.git/hooks/pre-commit`\n * that delegates to the CLI. Refuses to overwrite an existing hook\n * unless --force.\n */\nconst HOOK_MARKER = '# ddt-managed-hook';\n\nconst HOOK_BODY = `#!/bin/sh\n${HOOK_MARKER} — installed by \\`ddt install-hooks\\`. Remove this hook or re-install with --force to update.\n\n# Find the project file relative to the repo root.\nproject=$(find . -maxdepth 3 -name '*.ddtproj' -not -path '*/node_modules/*' -not -path '*/dist/*' | head -1)\nif [ -z \"$project\" ]; then\n echo \"ddt pre-commit hook: no .ddtproj found (skipping).\"\n exit 0\nfi\n\necho \"ddt pre-commit: validate + format-check on $project\"\n\nif ! command -v ddt >/dev/null 2>&1; then\n echo \"ddt CLI not on PATH. Install with \\`npm i -g @ddt-tools/cli\\`, or remove the hook at .git/hooks/pre-commit.\"\n exit 1\nfi\n\nif ! ddt validate -p \"$project\"; then\n echo \"\"\n echo \"Refusing commit: \\`ddt validate\\` failed.\"\n exit 1\nfi\n\nif ! ddt format -p \"$project\" --check; then\n echo \"\"\n echo \"Refusing commit: some .sql files are not formatted. Run \\`ddt format -p $project\\` and re-stage.\"\n exit 1\nfi\n`;\n\nexport function installHooksCommand(): Command {\n const cmd = new Command('install-hooks');\n cmd\n .description(\n 'Install a git pre-commit hook that runs `ddt validate` + `ddt format --check` before each commit.',\n )\n .option('--force', 'Overwrite an existing hook (refuses by default if the file exists).', false)\n .option('--uninstall', 'Remove the ddt-managed pre-commit hook instead of installing.', false)\n .action(async (opts) => {\n const cwd = process.cwd();\n const gitDir = await findGitDir(cwd);\n if (!gitDir) {\n throw new Error(`No .git directory found at or above ${cwd}.`);\n }\n const hookPath = path.join(gitDir, 'hooks', 'pre-commit');\n\n if (opts.uninstall) {\n if (!existsSync(hookPath)) {\n console.log('No pre-commit hook installed.');\n return;\n }\n const existing = await fs.readFile(hookPath, 'utf8');\n if (!existing.includes(HOOK_MARKER)) {\n console.error(\n `Refusing to remove: ${hookPath} is not a ddt-managed hook (missing marker).`,\n );\n process.exitCode = 1;\n return;\n }\n await fs.unlink(hookPath);\n console.log(`Removed ${hookPath}.`);\n return;\n }\n\n if (existsSync(hookPath) && !opts.force) {\n const existing = await fs.readFile(hookPath, 'utf8');\n if (existing.includes(HOOK_MARKER)) {\n console.log(`Hook already installed at ${hookPath}. Re-run with --force to overwrite.`);\n } else {\n console.error(`Refusing to overwrite: ${hookPath} exists and is NOT a ddt-managed hook.`);\n console.error('Inspect it, then re-run with --force if you want to replace it.');\n process.exitCode = 1;\n }\n return;\n }\n\n await fs.mkdir(path.dirname(hookPath), { recursive: true });\n await fs.writeFile(hookPath, HOOK_BODY, { mode: 0o755 });\n console.log(`Installed pre-commit hook at ${hookPath}.`);\n console.log(' Runs `ddt validate` + `ddt format --check` on every commit.');\n console.log(\n ' Bypass once with `git commit --no-verify`. Remove with `ddt install-hooks --uninstall`.',\n );\n });\n return cmd;\n}\n\nasync function findGitDir(start: string): Promise<string | undefined> {\n let dir = path.resolve(start);\n while (true) {\n const candidate = path.join(dir, '.git');\n if (existsSync(candidate)) {\n // Could be a regular dir or a `gitdir: …` pointer (worktree). Both work for hooks/.\n const stat = await fs.stat(candidate);\n if (stat.isDirectory()) return candidate;\n // Worktree: read the pointer.\n const ptr = await fs.readFile(candidate, 'utf8');\n const m = ptr.match(/^gitdir:\\s*(.+)$/m);\n if (m && m[1]) {\n const resolved = path.isAbsolute(m[1]) ? m[1] : path.resolve(dir, m[1]);\n return resolved;\n }\n }\n const parent = path.dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n}\n","import { Command } from 'commander';\nimport { errorReport, telemetry } from '@ddt-tools/core';\n\n/**\n * `ddt telemetry` — opt-in pseudonymous usage analytics AND automatic error\n * reporting (ERR.2: one consent governs both). Off by default.\n *\n * Subcommands:\n * on [--endpoint <url>] enable, optionally with an upload endpoint\n * off disable + stop recording\n * show print the last N recorded events\n * clear wipe local events\n * config print current config + error-reporting state\n */\nexport function telemetryCommand(): Command {\n const cmd = new Command('telemetry').description(\n 'Manage opt-in telemetry. Off by default; local-only by default.',\n );\n\n cmd\n .command('on')\n .description('Enable telemetry. By default events stay local; pass --endpoint to also upload.')\n .option('--endpoint <url>', 'Optional HTTPS upload endpoint.')\n .action(async (opts) => {\n const cfg: telemetry.TelemetryConfig = {\n enabled: true,\n enabledAt: new Date().toISOString(),\n ...(opts.endpoint ? { endpoint: String(opts.endpoint) } : {}),\n };\n await telemetry.saveConfig(cfg);\n // ERR.2 — one consent governs telemetry + automatic error reporting.\n await errorReport.writeConsent('on');\n console.log('Telemetry: ON.');\n console.log('Automatic error reporting enabled.');\n console.log(`Events written to ${telemetry.telemetryDir()}.`);\n if (cfg.endpoint) {\n console.log(\n `Will batch-upload to ${cfg.endpoint}. Run \\`ddt telemetry upload\\` to push pending events.`,\n );\n }\n });\n\n cmd\n .command('upload')\n .description('POST any not-yet-uploaded local events to the configured --endpoint.')\n .action(async () => {\n const cfg = await telemetry.loadConfig();\n const r = await telemetry.uploadPendingEvents(cfg);\n if (r.skipped) {\n console.log(`Upload skipped: ${r.reason}.`);\n return;\n }\n if (r.uploaded === 0) {\n console.log('No new events to upload.');\n return;\n }\n console.log(\n `Uploaded ${r.uploaded} event(s) to ${cfg.endpoint}.${r.reason ? ' (' + r.reason + ')' : ''}`,\n );\n });\n\n cmd\n .command('off')\n .description('Disable telemetry. Local events are NOT wiped — run `clear` for that.')\n .action(async () => {\n await telemetry.saveConfig({ enabled: false });\n // ERR.2 — disabling telemetry also opts out of automatic error reporting.\n await errorReport.writeConsent('off');\n console.log('Telemetry: OFF.');\n console.log('Automatic error reporting disabled.');\n console.warn(errorReport.CONSENT_WARNING);\n });\n\n cmd\n .command('show')\n .description('Print recent telemetry events (newest first).')\n .option('--limit <n>', 'Show this many events.', '20')\n .action(async (opts) => {\n const events = await telemetry.listEvents(parseInt(String(opts.limit), 10));\n const cfg = await telemetry.loadConfig();\n console.log(\n `Telemetry: ${cfg.enabled ? 'ON' : 'OFF'}${cfg.endpoint ? ' (endpoint=' + cfg.endpoint + ')' : ''}`,\n );\n console.log(`Storage: ${telemetry.telemetryDir()}`);\n console.log(`Events: ${events.length}`);\n console.log('');\n for (const e of events) {\n console.log(\n ` ${e.ts} ${e.command.padEnd(12)} ${e.platform.padEnd(11)} ${e.result.padEnd(8)} ${e.duration_ms}ms`,\n );\n }\n });\n\n cmd\n .command('clear')\n .description('Wipe every locally-recorded telemetry event.')\n .action(async () => {\n await telemetry.clearEvents();\n console.log('Telemetry: cleared all local events.');\n });\n\n cmd\n .command('config')\n .description('Print the telemetry config + automatic error-reporting state.')\n .action(async () => {\n const cfg = await telemetry.loadConfig();\n console.log(JSON.stringify(cfg, null, 2));\n\n // ERR.2 — error-reporting consent + local spool state.\n const consent = await errorReport.readConsent();\n const reportingEnabled = errorReport.isErrorReportingEnabled(consent.consent);\n const spooled = await errorReport.listSpooled();\n console.log(\n `Error reporting: ${consent.consent} (sending ${reportingEnabled ? 'enabled' : 'disabled'})`,\n );\n if (spooled.length > 0) {\n const occurrences = spooled.reduce((total, record) => total + record.count, 0);\n console.log(\n `Locally captured errors: ${spooled.length} distinct (${occurrences} occurrences) awaiting ${reportingEnabled ? 'upload' : 'consent'}.`,\n );\n }\n if (!reportingEnabled) console.log(` ${errorReport.CONSENT_WARNING}`);\n });\n\n return cmd;\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport {\n DatabricksExecutor,\n createConnection,\n discoverSeeds,\n getProfile,\n loadProject,\n renderSeedMerge,\n} from '@ddt-tools/core';\n\n/**\n * `ddt seed` — declare static reference rows next to DDL; engine\n * generates MERGE statements to keep them in sync.\n *\n * Subcommands:\n * list enumerate seed files + row counts\n * render -p <project> emit MERGEs to stdout (offline)\n * apply -p <project> -c <conn> execute the MERGEs against a workspace\n */\nexport function seedCommand(): Command {\n const cmd = new Command('seed').description(\n 'Reference / dimension data seeds. Declare static rows next to DDL; engine generates MERGEs.',\n );\n\n cmd\n .command('list')\n .description('Enumerate seed files under <project>/seeds/.')\n .requiredOption('-p, --project <path>', 'Path to the .ddtproj file.')\n .action(async (opts) => {\n const loaded = await loadProject(String(opts.project));\n const seeds = await discoverSeeds(loaded.rootDir);\n if (seeds.length === 0) {\n console.log(\n 'No seeds found. Add files under <project>/seeds/<catalog>/<schema>/<table>.{json,csv}.',\n );\n return;\n }\n for (const s of seeds) {\n console.log(\n ` ${s.catalog}.${s.schema}.${s.table.padEnd(28)} ${String(s.rows.length).padStart(5)} rows keys=[${s.keys.join(', ')}]`,\n );\n }\n console.log('');\n console.log(`${seeds.length} seed(s).`);\n });\n\n cmd\n .command('render')\n .description('Emit MERGE statements for every seed file. Offline; no workspace contact.')\n .requiredOption('-p, --project <path>', 'Path to the .ddtproj file.')\n .option('-o, --out <path>', 'Write to file. Defaults to stdout.')\n .option(\n '--delete-not-in-source',\n 'Add `WHEN NOT MATCHED BY SOURCE THEN DELETE` so target-only rows are removed. Default off (safer).',\n false,\n )\n .action(async (opts) => {\n const loaded = await loadProject(String(opts.project));\n const seeds = await discoverSeeds(loaded.rootDir);\n const renderOpts = { deleteNotInSource: !!opts.deleteNotInSource };\n const sql = seeds.map((s) => renderSeedMerge(s, renderOpts)).join('\\n\\n') + '\\n';\n if (opts.out) {\n const outPath = path.resolve(String(opts.out));\n await fs.mkdir(path.dirname(outPath), { recursive: true });\n await fs.writeFile(outPath, sql, 'utf8');\n console.error(`Wrote ${outPath} (${sql.length} bytes, ${seeds.length} seed(s)).`);\n } else {\n process.stdout.write(sql);\n }\n });\n\n cmd\n .command('apply')\n .description('Execute every seed MERGE against a connection profile.')\n .requiredOption('-p, --project <path>', 'Path to the .ddtproj file.')\n .requiredOption('--connection <name>', 'Connection profile to apply against.')\n .requiredOption('--yes', 'Explicit confirmation. Required because apply writes data.')\n .option('--dry-run', 'Print the MERGEs without executing.', false)\n .option(\n '--delete-not-in-source',\n 'Add `WHEN NOT MATCHED BY SOURCE THEN DELETE` so target-only rows are removed. Default off (safer).',\n false,\n )\n .action(async (opts) => {\n const loaded = await loadProject(String(opts.project));\n const seeds = await discoverSeeds(loaded.rootDir);\n if (seeds.length === 0) {\n console.log('No seeds found. Nothing to apply.');\n return;\n }\n const renderOpts = { deleteNotInSource: !!opts.deleteNotInSource };\n if (opts.dryRun) {\n for (const s of seeds) console.log(renderSeedMerge(s, renderOpts) + '\\n');\n return;\n }\n const profile = await getProfile(String(opts.connection));\n const conn = createConnection(profile);\n let succeeded = 0;\n let failed = 0;\n try {\n await conn.connect();\n const exec = new DatabricksExecutor(conn);\n for (const s of seeds) {\n process.stdout.write(`▶ ${s.catalog}.${s.schema}.${s.table} (${s.rows.length} rows) …`);\n const t0 = Date.now();\n try {\n await exec.execute(renderSeedMerge(s, renderOpts));\n console.log(` ✓ (${Date.now() - t0}ms)`);\n succeeded++;\n } catch (err) {\n console.log(` ✗ ${err instanceof Error ? err.message : String(err)}`);\n failed++;\n }\n }\n } finally {\n await conn.disconnect();\n }\n console.log('');\n console.log(`Summary: ${succeeded} succeeded, ${failed} failed.`);\n if (failed > 0) process.exitCode = 1;\n });\n\n return cmd;\n}\n","import path from 'node:path';\nimport { Command } from 'commander';\nimport {\n loadSuite,\n newSuiteTemplate,\n saveSuite,\n validateSuite,\n license as licenseNs,\n type SuiteFinding,\n} from '@ddt-tools/core';\n\n/**\n * Surface a Pro-tier warning (warn-mode v0.1 — never blocks).\n * Both `suite init` and `suite validate` are Pro features.\n */\nasync function warnIfMissingLicense(feature: licenseNs.ProFeature): Promise<void> {\n const lic = await licenseNs.loadLicense();\n const r = licenseNs.checkProFeature(lic, feature);\n if (r.warning) console.error(`[Pro] ${r.warning}`);\n}\n\n/**\n * `ddt suite` — manage and validate a `.ddtsuite` file, the collection of\n * `.ddtproj` projects that compose into one Databricks target.\n *\n * Subcommands:\n * init — scaffold a new .ddtsuite from a list of project paths\n * validate — run the 5 suite-level checks (ownership, refs, cycles,\n * coverage, deploy order)\n *\n * Pro-tier feature.\n */\nexport function suiteCommand(): Command {\n const cmd = new Command('suite').description(\n 'Manage a .ddtsuite — a collection of .ddtproj projects deploying together.',\n );\n cmd.addCommand(suiteInitCommand());\n cmd.addCommand(suiteValidateCommand());\n return cmd;\n}\n\nfunction suiteInitCommand(): Command {\n const cmd = new Command('init');\n cmd\n .description('Scaffold a new .ddtsuite file from a list of project paths.')\n .requiredOption('--out <path>', 'Where to write the new .ddtsuite file.')\n .requiredOption('--name <suite-name>', 'Suite display name.')\n .option(\n '--project <alias=path>',\n 'Add a project to the suite (repeatable). Format: alias=path/to/Project.ddtproj',\n (value: string, prev: Array<{ alias: string; path: string }>) => {\n const m = /^([A-Za-z_][\\w-]*)=(.+)$/.exec(value);\n if (!m) throw new Error(`Bad --project value \"${value}\". Expected alias=path.`);\n return [...prev, { alias: m[1]!, path: m[2]! }];\n },\n [] as Array<{ alias: string; path: string }>,\n )\n .action(async (opts) => {\n await warnIfMissingLicense('suite');\n const projects = opts.project as Array<{ alias: string; path: string }>;\n if (projects.length === 0) {\n throw new Error('At least one --project alias=path is required.');\n }\n const outPath = path.resolve(String(opts.out));\n const suite = newSuiteTemplate(String(opts.name), projects);\n await saveSuite(outPath, suite);\n console.log(`Wrote suite: ${outPath} (${projects.length} project(s))`);\n });\n return cmd;\n}\n\nfunction suiteValidateCommand(): Command {\n const cmd = new Command('validate');\n cmd\n .description('Validate a .ddtsuite: ownership conflicts, refs, cycles, deploy order.')\n .argument('<suite>', 'Path to a .ddtsuite file.')\n .option('--json', 'Emit machine-readable JSON.', false)\n .action(async (suiteArg: string, opts) => {\n await warnIfMissingLicense('suite');\n const loaded = await loadSuite(suiteArg);\n const result = validateSuite(loaded);\n if (opts.json) {\n process.stdout.write(JSON.stringify(result, null, 2) + '\\n');\n } else {\n printSuiteValidation(loaded.suite.suiteName, result.findings, result.deployOrder);\n }\n const errors = result.findings.filter((f) => f.severity === 'ERROR').length;\n if (errors > 0) process.exitCode = 2;\n });\n return cmd;\n}\n\nfunction printSuiteValidation(\n suiteName: string,\n findings: SuiteFinding[],\n deployOrder: string[],\n): void {\n console.log(`Suite: ${suiteName}`);\n const errors = findings.filter((f) => f.severity === 'ERROR');\n const warnings = findings.filter((f) => f.severity === 'WARNING');\n const infos = findings.filter((f) => f.severity === 'INFO');\n console.log(` ${errors.length} error(s), ${warnings.length} warning(s), ${infos.length} info`);\n for (const f of [...errors, ...warnings, ...infos]) {\n const tag = f.severity === 'ERROR' ? 'ERROR' : f.severity === 'WARNING' ? 'WARN ' : 'INFO ';\n console.log(` [${tag}] ${f.code}: ${f.message}`);\n }\n if (deployOrder.length > 0) {\n console.log(` Deploy order: ${deployOrder.join(' → ')}`);\n } else {\n console.error(` Suite is undeployable (cycle or invalid order).`);\n }\n}\n","/**\n * `ddt refactor` — record refactor operations (renames, moves, type changes)\n * in `refactor.json` so the compare engine emits `ALTER … RENAME` rather\n * than DROP + CREATE pairs.\n *\n * Mirrors `sdt refactor`. The DDT compare engine consumes the log via\n * `applyRefactorLogToResult` already (shipped earlier as the refactor-log\n * overlay).\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { refactoring } from '@ddt-tools/core';\n\nconst DEFAULT_LOG = './refactor.json';\nconst {\n appendOperation,\n loadRefactorLog,\n saveRefactorLog,\n REFACTOR_LOG_VERSION,\n extractCte,\n planRenameObject,\n applyRenamePlan,\n planMoveObject,\n buildRefactorDiff,\n renderRefactorDiffMarkdown,\n} = refactoring;\n\nfunction splitFqn(fqn: string): { database?: string; schema?: string; name: string } {\n const parts = fqn.split('.');\n if (parts.length === 1) return { name: parts[0]! };\n if (parts.length === 2) return { schema: parts[0]!, name: parts[1]! };\n return { database: parts[0]!, schema: parts[1]!, name: parts.slice(2).join('.') };\n}\n\nasync function ensureLogExists(p: string): Promise<refactoring.RefactorLog> {\n try {\n return await loadRefactorLog(p);\n } catch {\n return { version: REFACTOR_LOG_VERSION, operations: [] };\n }\n}\n\nexport function refactorCommand(): Command {\n const cmd = new Command('refactor').description(\n 'Record refactor operations (renames, moves) so compare emits ALTER … RENAME.',\n );\n\n cmd\n .command('rename')\n .description(\n 'Rename a column or object — recorded in refactor.json so compare emits ALTER RENAME.',\n )\n .requiredOption('--object <fqn>', 'Fully-qualified object name (e.g. catalog.schema.table)')\n .requiredOption('--new-name <name>', 'New name for the object')\n .requiredOption('--object-type <type>', 'Databricks object type (TABLE, VIEW, FUNCTION, …)')\n .option('--column <name>', 'Column name to rename — omit to rename the object itself')\n .option('--log <path>', `Path to refactor.json (default: ${DEFAULT_LOG})`)\n .option('--note <text>', 'Optional free-form note explaining the rename')\n .option(\n '--dry-run',\n 'Print the op that would be recorded, but do not write refactor.json',\n false,\n )\n .action(\n async (opts: {\n object: string;\n newName: string;\n objectType: string;\n column?: string;\n log?: string;\n note?: string;\n dryRun?: boolean;\n }) => {\n const logPath = path.resolve(opts.log ?? DEFAULT_LOG);\n const log = await ensureLogExists(logPath);\n const fqn = splitFqn(opts.object);\n const objectRef = { ...fqn, objectType: opts.objectType as never };\n const op = opts.column\n ? {\n type: 'RENAME_COLUMN' as const,\n object: objectRef,\n details: { oldName: opts.column, newName: opts.newName },\n ...(opts.note ? { note: opts.note } : {}),\n }\n : {\n type: 'RENAME_OBJECT' as const,\n object: objectRef,\n details: { oldName: fqn.name, newName: opts.newName },\n ...(opts.note ? { note: opts.note } : {}),\n };\n if (opts.dryRun) {\n console.log(\n `[dry-run] would record ${op.type} on ${opts.object}${opts.column ? `.${opts.column}` : ''} → ${opts.newName} (${logPath})`,\n );\n return;\n }\n const updated = appendOperation(log, op);\n await fs.mkdir(path.dirname(logPath), { recursive: true });\n await saveRefactorLog(logPath, updated);\n console.log(\n `Recorded ${op.type} on ${opts.object}${opts.column ? `.${opts.column}` : ''} → ${opts.newName} (${logPath})`,\n );\n },\n );\n\n cmd\n .command('move')\n .description('Move an object to a different schema / catalog — recorded as MOVE_OBJECT.')\n .requiredOption('--from <fqn>', 'Old FQN (e.g. oldcat.oldschema.name)')\n .requiredOption('--to <fqn>', 'New FQN')\n .requiredOption('--object-type <type>', 'Databricks object type')\n .option('--log <path>', `Path to refactor.json (default: ${DEFAULT_LOG})`)\n .option('--note <text>', 'Optional note')\n .option(\n '--dry-run',\n 'Print the op that would be recorded, but do not write refactor.json',\n false,\n )\n .action(\n async (opts: {\n from: string;\n to: string;\n objectType: string;\n log?: string;\n note?: string;\n dryRun?: boolean;\n }) => {\n const logPath = path.resolve(opts.log ?? DEFAULT_LOG);\n const log = await ensureLogExists(logPath);\n const oldFqn = splitFqn(opts.from);\n const newFqn = splitFqn(opts.to);\n const op = {\n type: 'MOVE_OBJECT' as const,\n object: { ...oldFqn, objectType: opts.objectType as never },\n details: { oldFqn, newFqn },\n ...(opts.note ? { note: opts.note } : {}),\n };\n if (opts.dryRun) {\n console.log(`[dry-run] would record MOVE_OBJECT ${opts.from} → ${opts.to} (${logPath})`);\n return;\n }\n const updated = appendOperation(log, op);\n await fs.mkdir(path.dirname(logPath), { recursive: true });\n await saveRefactorLog(logPath, updated);\n console.log(`Recorded MOVE_OBJECT ${opts.from} → ${opts.to} (${logPath})`);\n },\n );\n\n cmd\n .command('list')\n .description('List recorded refactor operations in chronological order.')\n .option('--log <path>', `Path to refactor.json (default: ${DEFAULT_LOG})`)\n .option(\n '--type <kind>',\n 'Filter by op kind (RENAME_OBJECT, RENAME_COLUMN, MOVE_OBJECT, CHANGE_COLUMN_TYPE, DROP_COLUMN, ADD_CONSTRAINT); case-insensitive',\n )\n .option(\n '--not-type <kind>',\n 'Exclude ops of this kind. Negation of --type — useful audit filter (\"show me everything except RENAME_COLUMN ops\"). Case-insensitive; same VALID_OP_KINDS list as --type. Mutually exclusive with --type (intersection of include + exclude on the same axis is a contradiction).',\n )\n .option(\n '--types <kinds>',\n 'Filter to ops whose kind is in this comma-separated list (case-insensitive). Plural form of --type — useful audit filter (\"--types RENAME_OBJECT,MOVE_OBJECT\" finds every object-shape-changing op without two passes). Each value must be a VALID_OP_KIND; whitespace around commas is trimmed. Mutually exclusive with --type and --not-type.',\n )\n .option(\n '--not-types <kinds>',\n 'Exclude ops whose kind is in this comma-separated list (case-insensitive). Plural negation of --type — useful audit filter (\"--not-types ADD_CONSTRAINT,DROP_COLUMN\" finds every op that is neither). Each value must be a VALID_OP_KIND; whitespace around commas is trimmed. Mutually exclusive with --type, --not-type, and --types.',\n )\n .option(\n '--since <iso>',\n 'Filter to ops with timestamp >= this ISO 8601 instant. Composes with --type (intersection). Mutually exclusive with --since-relative.',\n )\n .option(\n '--since-relative <duration>',\n 'Filter to ops with timestamp >= now - <duration>. Parse: N followed by unit `h` (hours) / `d` (days) / `w` (weeks = 7d) / `mo` (months = 30d). Examples: `7d` (last week), `24h` (last day), `2w` (last 14 days), `3mo` (last quarter). Mutually exclusive with --since.',\n )\n .option(\n '--until <iso>',\n 'Filter to ops with timestamp <= this ISO 8601 instant. Inclusive on equality. Composes with --since for a date-range and --type as intersection. Mutually exclusive with --until-relative.',\n )\n .option(\n '--until-relative <duration>',\n 'Filter to ops with timestamp <= now - <duration>. Same grammar as --since-relative (7d/24h/2w/3mo). Composes with --since-relative for relative closed-range windows. Useful for \"ops older than 6 months\" cleanup queries. Mutually exclusive with --until.',\n )\n .option(\n '--last <n>',\n 'After type/since/until filters, keep only the last N ops in chronological order. Refuses n <= 0. Mutually exclusive with --first.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--first <n>',\n 'After type/since/until filters, keep only the first N ops in chronological order. Refuses n <= 0. Mutually exclusive with --last.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--year <n>',\n 'Filter to ops whose timestamp falls in calendar year n (UTC). Useful for time-slice audits (\"--year 2026\" finds every refactor done in 2026 regardless of month/day). Opens a new TIMESTAMP CALENDAR-PART sub-arc on the refactor-list filter surface, mirroring the contains-any (iters 291-300), contains-all (iters 301-310), regex (iters 311-320), HAS/MISSING-IDENT (iters 321-324), and LENGTH (iters 325-334) sub-arcs. First flag of an expected paired sub-arc covering year + month + day-of-week + hour. n must be a non-negative integer; non-numeric or negative refuses with exit 1. Ops with no timestamp or unparseable timestamp are excluded. Composes orthogonally with --since/--until (intersection — both windows apply) and with --type as intersection.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--years <list>',\n 'Filter to ops whose timestamp (UTC) falls in ANY calendar year in this comma-separated list. Plural OR-semantics form of --year — useful audit filter (\"--years 2024,2025\" finds every refactor across two years in a single pass without two queries). Each value must be a non-negative integer; non-numeric or negative entry refuses with exit 1. Whitespace around commas is trimmed. Empty list refuses with exit 1. Ops with no timestamp or unparseable timestamp are excluded. Mutually exclusive with --year. Composes orthogonally with --since/--until/--type as intersection.',\n )\n .option(\n '--not-year <n>',\n 'Exclude ops whose timestamp (UTC) falls in calendar year n. Negation of --year — useful audit filter (\"--not-year 2024\" finds every refactor done outside 2024 in one pass). n must be a non-negative integer; non-numeric or negative refuses with exit 1. Ops with no timestamp or unparseable timestamp are KEPT (a missing timestamp does not fall in year n, so it isn\\'t excluded — symmetric with other --not-* axes). Mutually exclusive with --year and --years. Composes with --since/--until/--type as intersection.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--not-years <list>',\n 'Exclude ops whose timestamp (UTC) falls in ANY calendar year in this comma-separated list. Plural OR-negation of --year — useful audit filter (\"--not-years 2024,2025\" finds every refactor outside those two years in one pass). Each value must be a non-negative integer; non-numeric or negative entry refuses with exit 1. Whitespace around commas is trimmed. Empty list refuses with exit 1. Ops with no timestamp or unparseable timestamp are KEPT (symmetric with --not-year). Mutually exclusive with --year, --years, and --not-year. Composes with --since/--until/--type/--schema as intersection. Closes the year-axis quad (--year + --years + --not-year + --not-years) — 4 flags on the year axis of the TIMESTAMP CALENDAR-PART sub-arc.',\n )\n .option(\n '--month <n>',\n 'Filter to ops whose timestamp (UTC) falls in calendar month n (1=January, 12=December). Useful for seasonal / monthly audits (\"--month 12\" finds every refactor done in December regardless of year — handy for year-end change-window analysis). OPENS the month axis (2/4) of the TIMESTAMP CALENDAR-PART sub-arc, mirroring year axis (--year/--years/--not-year/--not-years, iters 335-338). n must be an integer in [1, 12]; out-of-range or non-numeric refuses with exit 1. Ops with no timestamp or unparseable timestamp are excluded. Composes orthogonally with --year/--years/--since/--until/--type as intersection.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--months <list>',\n 'Filter to ops whose timestamp (UTC) falls in ANY calendar month in this comma-separated list. Plural OR-semantics form of --month — useful for quarter audits (\"--months 1,2,3\" finds every Q1 refactor; \"--months 12,1,2\" finds every meteorological-winter refactor regardless of year). Each value must be an integer in [1, 12]; out-of-range or non-numeric entry refuses with exit 1. Whitespace around commas is trimmed. Empty list refuses with exit 1. Ops with no timestamp or unparseable timestamp are excluded. Mutually exclusive with --month. Composes orthogonally with --year/--years/--since/--until/--type as intersection.',\n )\n .option(\n '--not-month <n>',\n 'Exclude ops whose timestamp (UTC) falls in calendar month n (1-12). Negation of --month — useful audit filter (\"--not-month 12\" excludes year-end refactors). n must be an integer in [1, 12]; out-of-range or non-numeric refuses with exit 1. Ops with no timestamp or unparseable timestamp are KEPT (symmetric with other --not-* axes — missing field does not satisfy the predicate). Mutually exclusive with --month and --months. Composes orthogonally with --year/--years/--since/--until/--type as intersection.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--not-months <list>',\n 'Exclude ops whose timestamp (UTC) falls in ANY calendar month in this comma-separated list. Plural OR-negation of --month — useful for inverting season/quarter filters (\"--not-months 6,7,8\" excludes summer; \"--not-months 1,2,3\" excludes Q1). Each value must be an integer in [1, 12]; out-of-range or non-numeric entry refuses with exit 1. Whitespace around commas is trimmed. Empty list refuses with exit 1. Ops with no timestamp or unparseable timestamp are KEPT (symmetric with --not-month). Mutually exclusive with --month, --months, and --not-month. Composes orthogonally with --year/--years/--since/--until/--type/--schema as intersection. Closes the month-axis quad (--month + --months + --not-month + --not-months) — 4 flags on the month axis of the TIMESTAMP CALENDAR-PART sub-arc.',\n )\n .option(\n '--day-of-week <n>',\n 'Filter to ops whose timestamp (UTC) falls on calendar day-of-week n (0=Sunday, 1=Monday, ..., 6=Saturday — matches JS Date.getUTCDay convention). Useful for cadence audits (\"--day-of-week 6\" or \"--day-of-week 0\" finds weekend refactors — typically the higher-risk change windows worth auditing). OPENS the day-of-week axis (3/4) of the TIMESTAMP CALENDAR-PART sub-arc, mirroring the year and month axes. n must be an integer in [0, 6]; out-of-range or non-numeric refuses with exit 1. Ops with no timestamp or unparseable timestamp are excluded. Composes orthogonally with --year/--years/--month/--months/--since/--until/--type as intersection.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--days-of-week <list>',\n 'Filter to ops whose timestamp (UTC) falls on ANY day-of-week in this comma-separated list (0=Sun, 6=Sat). Plural OR-semantics form of --day-of-week — useful for weekend audits (\"--days-of-week 0,6\" finds every weekend refactor in one pass; \"--days-of-week 1,2,3,4,5\" finds every weekday refactor). Each value must be an integer in [0, 6]; out-of-range or non-numeric entry refuses with exit 1. Whitespace around commas is trimmed. Empty list refuses with exit 1. Ops with no timestamp or unparseable timestamp are excluded. Mutually exclusive with --day-of-week. Composes orthogonally with --year/--years/--month/--months/--since/--until/--type/--schema as intersection.',\n )\n .option(\n '--not-day-of-week <n>',\n 'Exclude ops whose timestamp (UTC) falls on calendar day-of-week n (0=Sunday, 1=Monday, ..., 6=Saturday — matches JS Date.getUTCDay convention). Negation of --day-of-week — useful for filtering out a noisy weekday from cadence audits (\"--not-day-of-week 0\" excludes Sunday refactors). 3/4 of the DAY-OF-WEEK axis of the TIMESTAMP CALENDAR-PART sub-arc, mirroring the not-year and not-month axes. n must be an integer in [0, 6]; out-of-range or non-numeric refuses with exit 1. Ops with no timestamp or unparseable timestamp are KEPT (symmetric with other --not-* axes — missing field does not satisfy the predicate). Mutually exclusive with --day-of-week and --days-of-week. Composes orthogonally with --year/--years/--month/--months/--since/--until/--type as intersection.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--not-days-of-week <list>',\n 'Exclude ops whose timestamp (UTC) falls on ANY day-of-week in this comma-separated list (0=Sun, 6=Sat). Plural OR-negation of --day-of-week — useful for inverting cadence filters (\"--not-days-of-week 0,6\" excludes every weekend refactor in one pass; \"--not-days-of-week 1,2,3,4,5\" excludes every weekday refactor). Each value must be an integer in [0, 6]; out-of-range or non-numeric entry refuses with exit 1. Whitespace around commas is trimmed. Empty list refuses with exit 1. Ops with no timestamp or unparseable timestamp are KEPT (symmetric with --not-day-of-week). Mutually exclusive with --day-of-week, --days-of-week, and --not-day-of-week. Composes orthogonally with --year/--years/--month/--months/--since/--until/--type/--schema as intersection. Closes the day-of-week axis quad (--day-of-week + --days-of-week + --not-day-of-week + --not-days-of-week) — 4 flags on the day-of-week axis of the TIMESTAMP CALENDAR-PART sub-arc.',\n )\n .option(\n '--hour <n>',\n 'Filter to ops whose timestamp (UTC) falls in calendar hour n (0-23 — matches JS Date.getUTCHours convention, 0=midnight..23=11pm). Useful for time-of-day cadence audits (\"--hour 22\" finds late-night refactors — typically the highest-risk change windows). OPENS the HOUR axis (4/4 — final axis) of the TIMESTAMP CALENDAR-PART sub-arc, mirroring the year, month, and day-of-week axes. n must be an integer in [0, 23]; out-of-range or non-numeric refuses with exit 1. Ops with no timestamp or unparseable timestamp are excluded. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--since/--until/--type as intersection.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--hours <list>',\n 'Filter to ops whose timestamp (UTC) falls in ANY calendar hour in this comma-separated list (0-23). Plural OR-semantics form of --hour — useful for time-window audits (\"--hours 22,23,0,1,2,3,4,5\" finds every late-night/early-morning refactor in one pass — the off-hours batch-job window; \"--hours 9,10,11,12,13,14,15,16,17\" finds every business-hour refactor). Each value must be an integer in [0, 23]; out-of-range or non-numeric entry refuses with exit 1. Whitespace around commas is trimmed. Empty list refuses with exit 1. Ops with no timestamp or unparseable timestamp are excluded. Mutually exclusive with --hour. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--since/--until/--type/--schema as intersection.',\n )\n .option(\n '--not-hour <n>',\n 'Exclude ops whose timestamp (UTC) falls in calendar hour n (0-23 — matches JS Date.getUTCHours convention, 0=midnight..23=11pm). Negation of --hour — useful for excluding noisy business-hours from off-hours audits (\"--not-hour 12\" excludes lunch-time refactors). 3/4 of the HOUR axis of the TIMESTAMP CALENDAR-PART sub-arc, mirroring the not-year, not-month, and not-day-of-week axes. n must be an integer in [0, 23]; out-of-range or non-numeric refuses with exit 1. Ops with no timestamp or unparseable timestamp are KEPT (symmetric with other --not-* axes — missing field does not satisfy the predicate). Mutually exclusive with --hour and --hours. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--since/--until/--type as intersection.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--not-hours <list>',\n 'Exclude ops whose timestamp (UTC) falls in ANY calendar hour in this comma-separated list (0-23). Plural OR-negation of --hour — useful for inverting time-window audits (\"--not-hours 9,10,11,12,13,14,15,16,17\" excludes every business-hour refactor — surfaces only off-hours work; \"--not-hours 0,1,2,3,4,5\" excludes early-morning ops). Each value must be an integer in [0, 23]; out-of-range or non-numeric entry refuses with exit 1. Whitespace around commas is trimmed. Empty list refuses with exit 1. Ops with no timestamp or unparseable timestamp are KEPT (symmetric with --not-hour). Mutually exclusive with --hour, --hours, and --not-hour. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--since/--until/--type/--schema as intersection. Closes the hour axis quad (--hour + --hours + --not-hour + --not-hours) — 4 flags on the hour axis, CLOSING THE TIMESTAMP CALENDAR-PART SUB-ARC (16 paired flags across 4 axes: year + month + day-of-week + hour).',\n )\n .option(\n '--minute <n>',\n 'Filter to ops whose timestamp (UTC) falls in calendar minute-of-hour n (0-59 — matches JS Date.getUTCMinutes convention). Useful for sub-hour cadence audits (\"--minute 0\" finds top-of-hour cron-job refactors; \"--minute 30\" finds half-hour cron-job refactors). OPENS a new TIMESTAMP MINUTE/SECOND sub-arc on the refactor-list filter surface (immediately following the now-closed TIMESTAMP CALENDAR-PART sub-arc that covered year/month/day-of-week/hour in 16 paired flags iters 335-350). First flag of a paired sub-arc covering minute-of-hour and second-of-minute. n must be an integer in [0, 59]; out-of-range or non-numeric refuses with exit 1. Ops with no timestamp or unparseable timestamp are excluded. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--hour/--hours/--since/--until/--type as intersection.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--minutes <list>',\n 'Filter to ops whose timestamp (UTC) falls in ANY calendar minute-of-hour in this comma-separated list (0-59). Plural OR-semantics form of --minute — useful for quarter-hour cadence audits (\"--minutes 0,15,30,45\" finds every quarter-hour cron-job refactor in one pass — the standard scheduled-job grid). Each value must be an integer in [0, 59]; out-of-range or non-numeric entry refuses with exit 1. Whitespace around commas is trimmed. Empty list refuses with exit 1. Ops with no timestamp or unparseable timestamp are excluded. Mutually exclusive with --minute. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--hour/--hours/--since/--until/--type/--schema as intersection.',\n )\n .option(\n '--not-minute <n>',\n 'Exclude ops whose timestamp (UTC) falls in calendar minute-of-hour n (0-59 — matches JS Date.getUTCMinutes convention). Negation of --minute — useful for excluding noisy scheduled-job minutes from ad-hoc cadence audits (\"--not-minute 0\" excludes top-of-hour cron-job refactors, surfacing only ad-hoc work). 3/4 of the MINUTE axis of the TIMESTAMP MINUTE/SECOND sub-arc. n must be an integer in [0, 59]; out-of-range or non-numeric refuses with exit 1. Ops with no timestamp or unparseable timestamp are KEPT (symmetric with other --not-* axes — missing field does not satisfy the predicate). Mutually exclusive with --minute and --minutes. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--hour/--hours/--since/--until/--type as intersection.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--not-minutes <list>',\n 'Exclude ops whose timestamp (UTC) falls in ANY calendar minute-of-hour in this comma-separated list (0-59). Plural OR-negation of --minute — useful for inverting scheduled-job cadence audits (\"--not-minutes 0,15,30,45\" excludes every quarter-hour cron-job refactor, surfacing only ad-hoc work outside the standard scheduled grid). Each value must be an integer in [0, 59]; out-of-range or non-numeric entry refuses with exit 1. Whitespace around commas is trimmed. Empty list refuses with exit 1. Ops with no timestamp or unparseable timestamp are KEPT (symmetric with --not-minute). Mutually exclusive with --minute, --minutes, and --not-minute. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--hour/--hours/--since/--until/--type/--schema as intersection. Closes the minute axis quad (--minute + --minutes + --not-minute + --not-minutes) — 4 flags on the minute axis of the TIMESTAMP MINUTE/SECOND sub-arc.',\n )\n .option(\n '--second <n>',\n 'Filter to ops whose timestamp (UTC) falls in calendar second-of-minute n (0-59 — matches JS Date.getUTCSeconds convention). Useful for sub-minute cadence audits (\"--second 0\" finds top-of-minute scheduled-job refactors; \"--second 30\" finds half-minute offset scheduled-job refactors). OPENS the SECOND axis (4/4) of the TIMESTAMP MINUTE/SECOND sub-arc — the MINUTE axis quad closed iter 354 (--minute + --minutes + --not-minute + --not-minutes). First flag of the SECOND axis quad. n must be an integer in [0, 59]; out-of-range or non-numeric refuses with exit 1. Ops with no timestamp or unparseable timestamp are excluded. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--hour/--hours/--minute/--minutes/--since/--until/--type as intersection.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--seconds <list>',\n 'Filter to ops whose timestamp (UTC) falls in ANY calendar second-of-minute in this comma-separated list (0-59). Plural OR-semantics form of --second — useful for sub-minute cadence audits (\"--seconds 0,15,30,45\" finds every quarter-minute scheduled-job refactor in one pass; \"--seconds 0,30\" finds top-of-minute + half-past). Each value must be an integer in [0, 59]; out-of-range or non-numeric entry refuses with exit 1. Whitespace around commas is trimmed. Empty list refuses with exit 1. Ops with no timestamp or unparseable timestamp are excluded. Mutually exclusive with --second. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--hour/--hours/--minute/--minutes/--since/--until/--type/--schema as intersection.',\n )\n .option(\n '--not-second <n>',\n 'Exclude ops whose timestamp (UTC) falls in calendar second-of-minute n (0-59 — matches JS Date.getUTCSeconds convention). Negation of --second — useful for excluding noisy scheduled-job seconds from ad-hoc cadence audits (\"--not-second 0\" excludes top-of-minute scheduled-job refactors, surfacing only ad-hoc work). 3/4 of the SECOND axis of the TIMESTAMP MINUTE/SECOND sub-arc. n must be an integer in [0, 59]; out-of-range or non-numeric refuses with exit 1. Ops with no timestamp or unparseable timestamp are KEPT (symmetric with other --not-* axes — missing field does not satisfy the predicate). Mutually exclusive with --second and --seconds. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--hour/--hours/--minute/--minutes/--since/--until/--type as intersection.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--not-seconds <list>',\n 'Exclude ops whose timestamp (UTC) falls in ANY calendar second-of-minute in this comma-separated list (0-59). Plural OR-negation of --second — useful for inverting scheduled-job cadence audits (\"--not-seconds 0,15,30,45\" excludes every quarter-minute cron-job refactor, surfacing only ad-hoc work outside the standard scheduled grid). Each value must be an integer in [0, 59]; out-of-range or non-numeric entry refuses with exit 1. Whitespace around commas is trimmed. Empty list refuses with exit 1. Ops with no timestamp or unparseable timestamp are KEPT (symmetric with --not-second). Mutually exclusive with --second, --seconds, and --not-second. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--hour/--hours/--minute/--minutes/--since/--until/--type/--schema as intersection. CLOSES the second axis quad (--second + --seconds + --not-second + --not-seconds) — 4 flags on the second axis, CLOSING THE TIMESTAMP MINUTE/SECOND SUB-ARC (8 paired flags across MINUTE + SECOND axes; combined with the 16-flag TIMESTAMP CALENDAR-PART sub-arc, this completes 24 paired timestamp-component flags spanning year/month/day-of-week/hour/minute/second).',\n )\n .option(\n '--day-of-month <n>',\n 'Filter to ops whose timestamp (UTC) falls on calendar day-of-month n (1-31 — matches JS Date.getUTCDate convention; note that this is the day-of-month, NOT the day-of-week — distinct from --day-of-week which targets 0-6 Sunday-Saturday). Useful for billing/payroll/audit cadence focus (\"--day-of-month 1\" finds first-of-month batch refactors; \"--day-of-month 15\" finds mid-month refactors; \"--day-of-month 31\" finds month-end refactors). OPENS a new TIMESTAMP DAY-OF-MONTH sub-arc on the refactor-list filter surface (immediately following the now-closed TIMESTAMP MINUTE/SECOND sub-arc that covered minute + second in 8 paired flags iters 351-358). First flag of a paired sub-arc covering day-of-month. n must be an integer in [1, 31]; out-of-range (including 0) or non-numeric refuses with exit 1. Ops with no timestamp or unparseable timestamp are excluded. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--hour/--hours/--minute/--minutes/--second/--seconds/--since/--until/--type as intersection.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--days-of-month <list>',\n 'Filter to ops whose timestamp (UTC) falls on ANY calendar day-of-month in this comma-separated list (1-31). Plural OR-semantics form of --day-of-month — useful for fiscal-period audits (\"--days-of-month 1,15\" finds twice-monthly payroll-cycle refactors; \"--days-of-month 1,7,14,21,28\" finds weekly-of-month cadence; \"--days-of-month 28,29,30,31\" finds month-end-window refactors regardless of month length). Each value must be an integer in [1, 31]; out-of-range (including 0) or non-numeric entry refuses with exit 1. Whitespace around commas is trimmed. Empty list refuses with exit 1. Ops with no timestamp or unparseable timestamp are excluded. Mutually exclusive with --day-of-month. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--hour/--hours/--minute/--minutes/--second/--seconds/--since/--until/--type/--schema as intersection.',\n )\n .option(\n '--not-day-of-month <n>',\n 'Exclude ops whose timestamp (UTC) falls on calendar day-of-month n (1-31 — matches JS Date.getUTCDate convention). Negation of --day-of-month — useful for excluding noisy month-boundary refactors from ad-hoc cadence audits (\"--not-day-of-month 1\" excludes first-of-month batch refactors, surfacing only mid-month ad-hoc work; \"--not-day-of-month 15\" excludes mid-month payroll ops). 3/4 of the DAY-OF-MONTH axis of the TIMESTAMP DAY-OF-MONTH sub-arc. n must be an integer in [1, 31]; out-of-range (including 0) or non-numeric refuses with exit 1. Ops with no timestamp or unparseable timestamp are KEPT (symmetric with other --not-* axes). Mutually exclusive with --day-of-month and --days-of-month. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--hour/--hours/--minute/--minutes/--second/--seconds/--since/--until/--type as intersection.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--not-days-of-month <list>',\n 'Exclude ops whose timestamp (UTC) falls on ANY calendar day-of-month in this comma-separated list (1-31). Plural OR-negation of --day-of-month — useful for inverting fiscal-period audits (\"--not-days-of-month 1,15\" excludes twice-monthly payroll-cycle refactors, surfacing only ad-hoc mid-period work; \"--not-days-of-month 28,29,30,31\" excludes month-end-window batches). Each value must be an integer in [1, 31]; out-of-range (including 0) or non-numeric entry refuses with exit 1. Whitespace around commas is trimmed. Empty list refuses with exit 1. Ops with no timestamp or unparseable timestamp are KEPT (symmetric with --not-day-of-month). Mutually exclusive with --day-of-month, --days-of-month, and --not-day-of-month. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--hour/--hours/--minute/--minutes/--second/--seconds/--since/--until/--type/--schema as intersection. CLOSES the day-of-month axis quad (--day-of-month + --days-of-month + --not-day-of-month + --not-days-of-month) — 4 flags on the day-of-month axis, CLOSING the DAY-OF-MONTH sub-arc (4 paired flags on the day-of-month axis; combined with the 24 prior timestamp-component flags spanning year/month/day-of-week/hour/minute/second, this completes 28 paired timestamp-component flags across SEVEN axes).',\n )\n .option(\n '--quarter <n>',\n 'Filter to ops whose timestamp (UTC) falls in calendar quarter n (1-4 — derived as Math.floor(Date.getUTCMonth() / 3) + 1; Q1=Jan-Mar, Q2=Apr-Jun, Q3=Jul-Sep, Q4=Oct-Dec). Useful for quarterly business-review focus (\"--quarter 4\" finds every Oct-Nov-Dec refactor for end-of-fiscal-year audit; \"--quarter 1\" finds every Jan-Feb-Mar refactor for start-of-year planning). OPENS a new TIMESTAMP QUARTER sub-arc on the refactor-list filter surface — the EIGHTH timestamp-component axis on the refactor-list filter surface (year + month + day-of-week + day-of-month + hour + minute + second already complete). First flag of a paired sub-arc covering quarter. n must be an integer in [1, 4]; out-of-range (including 0) or non-numeric refuses with exit 1. Ops with no timestamp or unparseable timestamp are excluded. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--day-of-month/--days-of-month/--hour/--hours/--minute/--minutes/--second/--seconds/--since/--until/--type as intersection.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--quarters <list>',\n 'Filter to ops whose timestamp (UTC) falls in ANY calendar quarter in this comma-separated list (1-4). Plural OR-semantics form of --quarter — useful for half-year/multi-quarter audits (\"--quarters 1,2\" finds every H1 refactor; \"--quarters 3,4\" finds every H2 refactor; \"--quarters 1,3\" finds odd-quarter refactors). Each value must be an integer in [1, 4]; out-of-range (including 0) or non-numeric entry refuses with exit 1. Whitespace around commas is trimmed. Empty list refuses with exit 1. Ops with no timestamp or unparseable timestamp are excluded. Mutually exclusive with --quarter. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--day-of-month/--days-of-month/--hour/--hours/--minute/--minutes/--second/--seconds/--since/--until/--type/--schema as intersection.',\n )\n .option(\n '--not-quarter <n>',\n 'Exclude ops whose timestamp (UTC) falls in calendar quarter n (1-4 — derived as Math.floor(Date.getUTCMonth() / 3) + 1; Q1=Jan-Mar, Q2=Apr-Jun, Q3=Jul-Sep, Q4=Oct-Dec). Negation of --quarter — useful for excluding seasonal noise from ad-hoc audits (\"--not-quarter 4\" excludes year-end Oct-Nov-Dec refactors, surfacing only first-three-quarter activity; \"--not-quarter 1\" excludes start-of-year planning ops). 3/4 of the QUARTER axis of the TIMESTAMP QUARTER sub-arc, mirroring the not-year, not-month, not-day-of-week, not-day-of-month, not-hour, not-minute, and not-second axes. n must be an integer in [1, 4]; out-of-range (including 0) or non-numeric refuses with exit 1. Ops with no timestamp or unparseable timestamp are KEPT (symmetric with other --not-* axes — missing field does not satisfy the predicate). Mutually exclusive with --quarter and --quarters. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--day-of-month/--days-of-month/--hour/--hours/--minute/--minutes/--second/--seconds/--since/--until/--type as intersection.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--not-quarters <list>',\n 'Exclude ops whose timestamp (UTC) falls in ANY calendar quarter in this comma-separated list (1-4). Plural OR-negation of --quarter — useful for inverting half-year/multi-quarter audits (\"--not-quarters 1,2\" excludes H1 refactors, surfacing only H2 activity; \"--not-quarters 3,4\" excludes H2 refactors; \"--not-quarters 1,3\" excludes odd-quarter refactors). Each value must be an integer in [1, 4]; out-of-range (including 0) or non-numeric entry refuses with exit 1. Whitespace around commas is trimmed. Empty list refuses with exit 1. Ops with no timestamp or unparseable timestamp are KEPT (symmetric with --not-quarter). Mutually exclusive with --quarter, --quarters, and --not-quarter. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--day-of-month/--days-of-month/--hour/--hours/--minute/--minutes/--second/--seconds/--since/--until/--type/--schema as intersection. CLOSES the quarter-axis quad (--quarter + --quarters + --not-quarter + --not-quarters) — 4 flags on the quarter axis, CLOSING THE TIMESTAMP QUARTER SUB-ARC.',\n )\n .option(\n '--day-of-year <n>',\n 'Filter to ops whose timestamp (UTC) falls on calendar day-of-year n (1-366; computed as floor((timestamp - Jan 1 of same year UTC) / 86400000) + 1). Useful for anniversary / fiscal-period audits (\"--day-of-year 1\" finds every Jan-1 New-Year-Day refactor across years; \"--day-of-year 60\" finds every Mar-1 in non-leap years and every Feb-29 in leap years; \"--day-of-year 366\" finds every leap-year Dec 31). OPENS a new TIMESTAMP DAY-OF-YEAR sub-arc on the refactor-list filter surface — the NINTH timestamp-component axis (year + month + day-of-week + day-of-month + hour + minute + second + quarter already complete iters 335-366). First flag of a paired sub-arc covering day-of-year. n must be an integer in [1, 366]; out-of-range (including 0) or non-numeric refuses with exit 1. Ops with no timestamp or unparseable timestamp are excluded. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--day-of-month/--days-of-month/--quarter/--quarters/--hour/--hours/--minute/--minutes/--second/--seconds/--since/--until/--type as intersection.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--days-of-year <list>',\n 'Filter to ops whose timestamp (UTC) falls on ANY calendar day-of-year in this comma-separated list (1-366). Plural OR-semantics form of --day-of-year — useful for multi-anniversary audits (\"--days-of-year 1,185,365\" finds every Jan-1 + Jul-4 + Dec-31 refactor in one pass — the US-civic-holiday trifecta; \"--days-of-year 60,61\" finds every Feb-29 (leap) + Mar-1 (non-leap)/Mar-1 (leap) ambiguous-window refactor). Each value must be an integer in [1, 366]; out-of-range (including 0) or non-numeric entry refuses with exit 1. Whitespace around commas is trimmed. Empty list refuses with exit 1. Ops with no timestamp or unparseable timestamp are excluded. Mutually exclusive with --day-of-year. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--day-of-month/--days-of-month/--quarter/--quarters/--hour/--hours/--minute/--minutes/--second/--seconds/--since/--until/--type/--schema as intersection.',\n )\n .option(\n '--not-day-of-year <n>',\n 'Exclude ops whose timestamp (UTC) falls on calendar day-of-year n (1-366; computed as floor((timestamp - Jan 1 of same year UTC) / 86400000) + 1). Negation of --day-of-year — useful for excluding anniversary noise from ad-hoc cadence audits (\"--not-day-of-year 1\" excludes Jan-1 New-Year-Day refactors; \"--not-day-of-year 365\" excludes year-end Dec-31 refactors). 3/4 of the DAY-OF-YEAR axis of the TIMESTAMP DAY-OF-YEAR sub-arc, mirroring the not-year, not-month, not-day-of-week, not-day-of-month, not-quarter, not-hour, not-minute, and not-second axes. n must be an integer in [1, 366]; out-of-range (including 0) or non-numeric refuses with exit 1. Ops with no timestamp or unparseable timestamp are KEPT (symmetric with other --not-* axes — missing field does not satisfy the predicate). Mutually exclusive with --day-of-year and --days-of-year. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--day-of-month/--days-of-month/--quarter/--quarters/--hour/--hours/--minute/--minutes/--second/--seconds/--since/--until/--type as intersection.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--not-days-of-year <list>',\n 'Exclude ops whose timestamp (UTC) falls on ANY calendar day-of-year in this comma-separated list (1-366). Plural OR-negation of --day-of-year — useful for inverting multi-anniversary audits (\"--not-days-of-year 1,185,365\" excludes US-civic-trifecta Jan-1 + Jul-4 + Dec-31 in one pass — surfaces non-holiday-anniversary refactors; \"--not-days-of-year 60,61\" excludes leap-bridge Feb-29 + Mar-1 ambiguous window). Each value must be an integer in [1, 366]; out-of-range (including 0) or non-numeric entry refuses with exit 1. Whitespace around commas is trimmed. Empty list refuses with exit 1. Ops with no timestamp or unparseable timestamp are KEPT (symmetric with --not-day-of-year). Mutually exclusive with --day-of-year, --days-of-year, and --not-day-of-year. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--day-of-month/--days-of-month/--quarter/--quarters/--hour/--hours/--minute/--minutes/--second/--seconds/--since/--until/--type/--schema as intersection. CLOSES the day-of-year axis quad (--day-of-year + --days-of-year + --not-day-of-year + --not-days-of-year) — 4 flags on the day-of-year axis, CLOSING THE TIMESTAMP DAY-OF-YEAR SUB-ARC. The 9th completed timestamp-component axis on the refactor-list filter surface (after year/month/day-of-week/day-of-month/hour/minute/second/quarter + day-of-year = 9 axes × 4 flags = 36 paired timestamp-component flags).',\n )\n .option(\n '--week-of-year <n>',\n 'Filter to ops whose timestamp (UTC) falls in calendar week-of-year n (1-53; computed as floor((timestamp - Jan 1 of same year UTC) / 86400000 / 7) + 1 — \"simple week\" definition where week 1 = days 1-7 of the year, week 2 = days 8-14, etc.). Useful for sprint / weekly cadence audits (\"--week-of-year 1\" finds every first-week-of-year refactor; \"--week-of-year 26\" finds every mid-year week-26 refactor; \"--week-of-year 53\" finds end-of-year overflow-week refactors which only exist in years where Dec 31 lands on day 365+). OPENS a new TIMESTAMP WEEK-OF-YEAR sub-arc on the refactor-list filter surface — the TENTH timestamp-component axis (year + month + day-of-week + day-of-month + hour + minute + second + quarter + day-of-year already complete iters 335-370). First flag of a paired sub-arc covering week-of-year. n must be an integer in [1, 53]; out-of-range (including 0) or non-numeric refuses with exit 1. Ops with no timestamp or unparseable timestamp are excluded. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--day-of-month/--days-of-month/--day-of-year/--days-of-year/--quarter/--quarters/--hour/--hours/--minute/--minutes/--second/--seconds/--since/--until/--type as intersection.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--weeks-of-year <list>',\n 'Filter to ops whose timestamp (UTC) falls in ANY calendar week-of-year in this comma-separated list (1-53). Plural OR-semantics form of --week-of-year — useful for multi-sprint audits (\"--weeks-of-year 1,2,3,4\" finds every January refactor (~first 4 weeks); \"--weeks-of-year 14,27,40\" finds quarter-boundary weeks; \"--weeks-of-year 1,53\" finds first + overflow week refactors). Each value must be an integer in [1, 53]; out-of-range (including 0) or non-numeric entry refuses with exit 1. Whitespace around commas is trimmed. Empty list refuses with exit 1. Ops with no timestamp or unparseable timestamp are excluded. Mutually exclusive with --week-of-year. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--day-of-month/--days-of-month/--day-of-year/--days-of-year/--quarter/--quarters/--hour/--hours/--minute/--minutes/--second/--seconds/--since/--until/--type/--schema as intersection.',\n )\n .option(\n '--not-week-of-year <n>',\n 'Exclude ops whose timestamp (UTC) falls in calendar week-of-year n (1-53; \"simple week\" definition where week 1 = days 1-7 of the year, etc.). Negation of --week-of-year — useful for excluding sprint-boundary noise from ad-hoc cadence audits (\"--not-week-of-year 1\" excludes first-week-of-year refactors; \"--not-week-of-year 53\" excludes year-end overflow-week refactors). 3/4 of the WEEK-OF-YEAR axis of the TIMESTAMP WEEK-OF-YEAR sub-arc, mirroring the not-year, not-month, not-day-of-week, not-day-of-month, not-quarter, not-day-of-year, not-hour, not-minute, and not-second axes. n must be an integer in [1, 53]; out-of-range (including 0) or non-numeric refuses with exit 1. Ops with no timestamp or unparseable timestamp are KEPT (symmetric with other --not-* axes). Mutually exclusive with --week-of-year and --weeks-of-year. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--day-of-month/--days-of-month/--day-of-year/--days-of-year/--quarter/--quarters/--hour/--hours/--minute/--minutes/--second/--seconds/--since/--until/--type as intersection.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--not-weeks-of-year <list>',\n 'Exclude ops whose timestamp (UTC) falls in ANY calendar week-of-year in this comma-separated list (1-53). Plural OR-negation of --week-of-year — useful for inverting multi-sprint audits (\"--not-weeks-of-year 1,2,3,4\" excludes January sprints surfacing only non-January refactors; \"--not-weeks-of-year 13,27,40\" excludes quarter-boundary weeks; \"--not-weeks-of-year 1,53\" excludes first + overflow week refactors). Each value must be an integer in [1, 53]; out-of-range (including 0) or non-numeric entry refuses with exit 1. Whitespace around commas is trimmed. Empty list refuses with exit 1. Ops with no timestamp or unparseable timestamp are KEPT (symmetric with --not-week-of-year). Mutually exclusive with --week-of-year, --weeks-of-year, and --not-week-of-year. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--day-of-month/--days-of-month/--day-of-year/--days-of-year/--quarter/--quarters/--hour/--hours/--minute/--minutes/--second/--seconds/--since/--until/--type/--schema as intersection. CLOSES the week-of-year axis quad (--week-of-year + --weeks-of-year + --not-week-of-year + --not-weeks-of-year) — 4 flags on the week-of-year axis, CLOSING THE TIMESTAMP WEEK-OF-YEAR SUB-ARC. The 10th completed timestamp-component axis on the refactor-list filter surface (after year + month + day-of-week + day-of-month + hour + minute + second + quarter + day-of-year + week-of-year = 10 axes × 4 flags = 40 paired timestamp-component flags).',\n )\n .option(\n '--week-of-month <n>',\n 'Filter to ops whose timestamp (UTC) falls in calendar week-of-month n (1-5; computed as floor((UTC day-of-month - 1) / 7) + 1 — \"simple week-of-month\" definition where week 1 = days 1-7 of the month, week 2 = days 8-14, week 3 = days 15-21, week 4 = days 22-28, week 5 = days 29-31 (only months with 29+ days)). Useful for intra-month cadence audits (\"--week-of-month 1\" finds every first-week-of-month refactor across all months — first-week-of-month sprint pattern; \"--week-of-month 5\" finds end-of-month refactors that landed on days 29-31, typically month-end batch jobs; \"--week-of-month 3\" finds mid-month refactors). OPENS a new TIMESTAMP WEEK-OF-MONTH sub-arc on the refactor-list filter surface — the ELEVENTH timestamp-component axis (year + month + day-of-week + day-of-month + hour + minute + second + quarter + day-of-year + week-of-year already complete iters 335-374). First flag of a paired sub-arc covering week-of-month. n must be an integer in [1, 5]; out-of-range (including 0) or non-numeric refuses with exit 1. Ops with no timestamp or unparseable timestamp are excluded. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--day-of-month/--days-of-month/--day-of-year/--days-of-year/--week-of-year/--weeks-of-year/--quarter/--quarters/--hour/--hours/--minute/--minutes/--second/--seconds/--since/--until/--type as intersection.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--weeks-of-month <list>',\n 'Filter to ops whose timestamp (UTC) falls in ANY calendar week-of-month in this comma-separated list (1-5). Plural OR-semantics form of --week-of-month — useful for multi-week intra-month audits (\"--weeks-of-month 1,5\" finds every first-week + last-week-of-month refactor across all months — bracket-of-month bookends; \"--weeks-of-month 1,2\" finds every early-month refactor (days 1-14); \"--weeks-of-month 4,5\" finds end-of-month refactors (days 22-31)). Each value must be an integer in [1, 5]; out-of-range (including 0) or non-numeric entry refuses with exit 1. Whitespace around commas is trimmed. Empty list refuses with exit 1. Ops with no timestamp or unparseable timestamp are excluded. Mutually exclusive with --week-of-month. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--day-of-month/--days-of-month/--day-of-year/--days-of-year/--week-of-year/--weeks-of-year/--quarter/--quarters/--hour/--hours/--minute/--minutes/--second/--seconds/--since/--until/--type/--schema as intersection.',\n )\n .option(\n '--not-week-of-month <n>',\n 'Exclude ops whose timestamp (UTC) falls in calendar week-of-month n (1-5; computed as floor((UTC day-of-month - 1) / 7) + 1 — \"simple week-of-month\" definition). Negation of --week-of-month — useful for excluding intra-month sprint noise from ad-hoc cadence audits (\"--not-week-of-month 1\" excludes first-week-of-month sprint refactors surfacing only mid/late-month work; \"--not-week-of-month 5\" excludes end-of-month batch-job refactors). 3/4 of the WEEK-OF-MONTH axis of the TIMESTAMP WEEK-OF-MONTH sub-arc, mirroring the not-year, not-month, not-day-of-week, not-day-of-month, not-quarter, not-day-of-year, not-week-of-year, not-hour, not-minute, and not-second axes. n must be an integer in [1, 5]; out-of-range (including 0) or non-numeric refuses with exit 1. Ops with no timestamp or unparseable timestamp are KEPT (symmetric with other --not-* axes — a missing field does not satisfy the predicate, so isn\\'t excluded). Mutually exclusive with --week-of-month and --weeks-of-month. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--day-of-month/--days-of-month/--day-of-year/--days-of-year/--week-of-year/--weeks-of-year/--quarter/--quarters/--hour/--hours/--minute/--minutes/--second/--seconds/--since/--until/--type as intersection.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--not-weeks-of-month <list>',\n 'Exclude ops whose timestamp (UTC) falls in ANY calendar week-of-month in this comma-separated list (1-5). Plural OR-negation of --week-of-month — useful for inverting multi-week intra-month audits (\"--not-weeks-of-month 1,5\" excludes first-week + last-week-of-month refactors surfacing only mid-month work (days 8-28); \"--not-weeks-of-month 1,2\" excludes early-month sprint refactors; \"--not-weeks-of-month 4,5\" excludes end-of-month batch refactors). Each value must be an integer in [1, 5]; out-of-range (including 0) or non-numeric entry refuses with exit 1. Whitespace around commas is trimmed. Empty list refuses with exit 1. Ops with no timestamp or unparseable timestamp are KEPT (symmetric with --not-week-of-month). Mutually exclusive with --week-of-month, --weeks-of-month, and --not-week-of-month. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--day-of-month/--days-of-month/--day-of-year/--days-of-year/--week-of-year/--weeks-of-year/--quarter/--quarters/--hour/--hours/--minute/--minutes/--second/--seconds/--since/--until/--type/--schema as intersection. CLOSES the week-of-month axis quad (--week-of-month + --weeks-of-month + --not-week-of-month + --not-weeks-of-month) — 4 flags on the week-of-month axis, CLOSING THE TIMESTAMP WEEK-OF-MONTH SUB-ARC. The 11th completed timestamp-component axis on the refactor-list filter surface (after year + month + day-of-week + day-of-month + hour + minute + second + quarter + day-of-year + week-of-year + week-of-month = 11 axes × 4 flags = 44 paired timestamp-component flags).',\n )\n .option(\n '--millisecond <n>',\n 'Filter to ops whose timestamp (UTC) has millisecond-of-second component n (0-999; the sub-second fraction, Date.getUTCMilliseconds()). Useful for diagnostic precision audits (\"--millisecond 0\" finds every refactor logged on a whole-second boundary — typically synthetic / test-seeded ops, since real wall-clock timestamps almost never land exactly on .000). OPENS a new TIMESTAMP MILLISECOND sub-arc on the refactor-list filter surface — the TWELFTH timestamp-component axis, completing the time-of-day component hierarchy hour → minute → second → millisecond (year + month + day-of-week + day-of-month + hour + minute + second + quarter + day-of-year + week-of-year + week-of-month already complete iters 335-378). First flag of a paired sub-arc covering millisecond. n must be an integer in [0, 999]; out-of-range or non-numeric refuses with exit 1. Ops with no timestamp or unparseable timestamp are excluded. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--day-of-month/--days-of-month/--day-of-year/--days-of-year/--week-of-year/--weeks-of-year/--week-of-month/--weeks-of-month/--quarter/--quarters/--hour/--hours/--minute/--minutes/--second/--seconds/--since/--until/--type as intersection.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--milliseconds <list>',\n 'Filter to ops whose timestamp (UTC) has millisecond-of-second component matching ANY value in this comma-separated list (0-999). Plural OR-semantics form of --millisecond — useful for multi-value diagnostic precision audits (\"--milliseconds 0,500\" finds every refactor on a whole-second or half-second boundary — synthetic / test-seeded ops; \"--milliseconds 0,250,500,750\" finds every quarter-second-boundary op). Each value must be an integer in [0, 999]; out-of-range or non-numeric entry refuses with exit 1. Whitespace around commas is trimmed. Empty list refuses with exit 1. Ops with no timestamp or unparseable timestamp are excluded. Mutually exclusive with --millisecond. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--day-of-month/--days-of-month/--day-of-year/--days-of-year/--week-of-year/--weeks-of-year/--week-of-month/--weeks-of-month/--quarter/--quarters/--hour/--hours/--minute/--minutes/--second/--seconds/--since/--until/--type/--schema as intersection.',\n )\n .option(\n '--not-millisecond <n>',\n 'Exclude ops whose timestamp (UTC) has millisecond-of-second component n (0-999; the sub-second fraction, Date.getUTCMilliseconds()). Negation of --millisecond — useful for excluding synthetic / test-seeded ops from precision audits (\"--not-millisecond 0\" excludes every whole-second-boundary refactor, surfacing only real wall-clock-timestamped ops). 3/4 of the MILLISECOND axis of the TIMESTAMP MILLISECOND sub-arc, mirroring the not-year, not-month, not-day-of-week, not-day-of-month, not-quarter, not-day-of-year, not-week-of-year, not-week-of-month, not-hour, not-minute, and not-second axes. n must be an integer in [0, 999]; out-of-range or non-numeric refuses with exit 1. Ops with no timestamp or unparseable timestamp are KEPT (symmetric with other --not-* axes — a missing field does not satisfy the predicate, so isn\\'t excluded). Mutually exclusive with --millisecond and --milliseconds. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--day-of-month/--days-of-month/--day-of-year/--days-of-year/--week-of-year/--weeks-of-year/--week-of-month/--weeks-of-month/--quarter/--quarters/--hour/--hours/--minute/--minutes/--second/--seconds/--since/--until/--type as intersection.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--not-milliseconds <list>',\n 'Exclude ops whose timestamp (UTC) has millisecond-of-second component matching ANY value in this comma-separated list (0-999). Plural OR-negation of --millisecond — useful for inverting multi-value precision audits (\"--not-milliseconds 0,500\" excludes every whole-second + half-second-boundary refactor, surfacing only off-grid real-wall-clock ops; \"--not-milliseconds 0,250,500,750\" excludes all quarter-second-boundary synthetic ops). Each value must be an integer in [0, 999]; out-of-range or non-numeric entry refuses with exit 1. Whitespace around commas is trimmed. Empty list refuses with exit 1. Ops with no timestamp or unparseable timestamp are KEPT (symmetric with --not-millisecond). Mutually exclusive with --millisecond, --milliseconds, and --not-millisecond. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--day-of-month/--days-of-month/--day-of-year/--days-of-year/--week-of-year/--weeks-of-year/--week-of-month/--weeks-of-month/--quarter/--quarters/--hour/--hours/--minute/--minutes/--second/--seconds/--since/--until/--type/--schema as intersection. CLOSES the millisecond axis quad (--millisecond + --milliseconds + --not-millisecond + --not-milliseconds) — 4 flags on the millisecond axis, CLOSING THE TIMESTAMP MILLISECOND SUB-ARC. The 12th completed timestamp-component axis on the refactor-list filter surface (after year + month + day-of-week + day-of-month + hour + minute + second + quarter + day-of-year + week-of-year + week-of-month + millisecond = 12 axes × 4 flags = 48 paired timestamp-component flags).',\n )\n .option(\n '--minute-of-day <n>',\n 'Filter to ops whose timestamp (UTC) falls at minute-of-day n (0-1439; computed as Date.getUTCHours() * 60 + Date.getUTCMinutes() — the count of minutes elapsed since UTC midnight). Useful for fine-grained time-of-day cadence audits in a single number (\"--minute-of-day 0\" finds every midnight-UTC refactor; \"--minute-of-day 720\" finds every noon-UTC refactor; \"--minute-of-day 1439\" finds the last-minute-of-day 23:59 refactors). OPENS a new TIMESTAMP MINUTE-OF-DAY sub-arc on the refactor-list filter surface — the THIRTEENTH timestamp-component axis, a composite single-number time-of-day axis (parallel to day-of-year which is a composite of month + day-of-month). First flag of a paired sub-arc covering minute-of-day. n must be an integer in [0, 1439]; out-of-range or non-numeric refuses with exit 1. Ops with no timestamp or unparseable timestamp are excluded. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--day-of-month/--days-of-month/--day-of-year/--days-of-year/--week-of-year/--weeks-of-year/--week-of-month/--weeks-of-month/--quarter/--quarters/--hour/--hours/--minute/--minutes/--second/--seconds/--millisecond/--milliseconds/--since/--until/--type as intersection.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--minutes-of-day <list>',\n 'Filter to ops whose timestamp (UTC) minute-of-day (Date.getUTCHours() * 60 + Date.getUTCMinutes(), 0-1439) matches ANY value in this comma-separated list. Plural OR-semantics form of --minute-of-day — useful for multi-window time-of-day audits (\"--minutes-of-day 0,720\" finds every midnight + noon refactor; \"--minutes-of-day 540,1020\" finds 09:00 + 17:00 work-day boundary refactors). Each value must be an integer in [0, 1439]; out-of-range or non-numeric entry refuses with exit 1. Whitespace around commas is trimmed. Empty list refuses with exit 1. Ops with no timestamp or unparseable timestamp are excluded. Mutually exclusive with --minute-of-day. Composes orthogonally with --year/--years/--month/--months/--day-of-week/--days-of-week/--day-of-month/--days-of-month/--day-of-year/--days-of-year/--week-of-year/--weeks-of-year/--week-of-month/--weeks-of-month/--quarter/--quarters/--hour/--hours/--minute/--minutes/--second/--seconds/--millisecond/--milliseconds/--since/--until/--type/--schema as intersection.',\n )\n .option(\n '--id <id>',\n 'Filter to the single op with this id. Composes with other filters as an additional intersection (useful for sanity-checking that op-X is within a time range).',\n )\n .option(\n '--ids <ids>',\n 'Filter to ops whose id equals any value in this comma-separated list (case-sensitive). Plural form of --id — useful audit filter (\"--ids op-abc,op-def,op-123\" pulls every named op in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --id and --not-id.',\n )\n .option(\n '--not-ids <ids>',\n 'Exclude ops whose id equals any value in this comma-separated list (case-sensitive). Plural negation of --id — useful audit filter (\"--not-ids op-abc,op-def,op-123\" finds every op except the named ones in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --id, --not-id, and --ids.',\n )\n .option(\n '--not-id <id>',\n 'Exclude the single op with this id (case-sensitive exact match). Negation of --id — useful precision audit filter (\"--not-id op-abc-123\" finds every op except that one without false-matching shared prefixes / suffixes). Mutually exclusive with --id.',\n )\n .option(\n '--id-prefix <prefix>',\n 'Filter to ops whose id starts with this prefix (case-sensitive). Useful when looking up an op by a truncated UUID from a CI log. Composes with other filters as intersection.',\n )\n .option(\n '--not-id-prefix <prefix>',\n 'Exclude ops whose id starts with this prefix (case-sensitive). Negation of --id-prefix — useful audit filter (\"--not-id-prefix abc123\" excludes every op generated by the abc123-* CI run). Mutually exclusive with --id-prefix.',\n )\n .option(\n '--id-prefixes <prefixes>',\n 'Filter to ops whose id starts with any prefix in this comma-separated list (case-sensitive). Plural OR-semantics form of --id-prefix — useful for multi-CI-run audits (\"--id-prefixes abc123,def456,ghi789\" finds every op from any of three CI runs in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --id-prefix and --not-id-prefix.',\n )\n .option(\n '--not-id-prefixes <prefixes>',\n 'Exclude ops whose id starts with any prefix in this comma-separated list (case-sensitive). Plural OR-negation of --id-prefix — useful audit filter (\"--not-id-prefixes abc123,def456,ghi789\" finds every op except those from three named CI runs in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --id-prefix, --not-id-prefix, and --id-prefixes.',\n )\n .option(\n '--id-suffix <suffix>',\n 'Filter to ops whose id ends with this suffix (case-sensitive). Mirror of --id-prefix. Useful when a CI log only shows the tail of a UUID (\"the op whose id ends in ...9bc\"). Composes with other filters as intersection.',\n )\n .option(\n '--not-id-suffix <suffix>',\n 'Exclude ops whose id ends with this suffix (case-sensitive). Negation of --id-suffix — useful audit filter (\"--not-id-suffix 9bc\" excludes ops whose UUID ends in that tail). Mutually exclusive with --id-suffix.',\n )\n .option(\n '--id-suffixes <suffixes>',\n 'Filter to ops whose id ends with any suffix in this comma-separated list (case-sensitive). Plural OR-semantics form of --id-suffix — useful for multi-CI-run audits when only the UUID tail is known (\"--id-suffixes 9bc,1f2,abc\" finds every op whose id ends in any of three tails in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --id-suffix and --not-id-suffix.',\n )\n .option(\n '--not-id-suffixes <suffixes>',\n 'Exclude ops whose id ends with any suffix in this comma-separated list (case-sensitive). Plural OR-negation of --id-suffix — useful audit filter (\"--not-id-suffixes 9bc,1f2,abc\" finds every op except those whose UUID ends in three named tails in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --id-suffix, --not-id-suffix, and --id-suffixes.',\n )\n .option(\n '--id-contains <substring>',\n 'Filter to ops whose id contains this substring (case-sensitive). Useful when only a middle segment of a UUID is known (e.g. an embedded request-id). Composes with --id-prefix + --id-suffix to bracket a known middle.',\n )\n .option(\n '--not-id-contains <substring>',\n 'Exclude ops whose id contains this substring (case-sensitive). Negation of --id-contains — useful audit filter (\"--not-id-contains abc\" excludes every op whose UUID embeds that mid-segment, leaving the rest). Mutually exclusive with --id-contains.',\n )\n .option(\n '--id-contains-any <substrings>',\n 'Filter to ops whose id contains ANY substring in this comma-separated list (case-sensitive — UUIDs are case-sensitive). Plural OR-semantics form of --id-contains — useful for multi-CI-run mid-id audits (\"--id-contains-any abc,def,ghi\" finds every op whose UUID embeds any of three known mid-segments in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --id-contains and --not-id-contains.',\n )\n .option(\n '--not-id-contains-any <substrings>',\n 'Exclude ops whose id contains ANY substring in this comma-separated list (case-sensitive). Plural OR-negation of --id-contains — useful audit filter (\"--not-id-contains-any abc,def,ghi\" finds every op except those whose UUID embeds any of three known mid-segments in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --id-contains, --not-id-contains, and --id-contains-any.',\n )\n .option(\n '--id-contains-all <substrings>',\n 'Filter to ops whose id contains EVERY substring in this comma-separated list (case-sensitive — UUIDs are case-sensitive, mirrors --id-contains and --id-contains-any). Plural AND-semantics form of --id-contains — useful for narrow CI-run audits where multiple mid-id segments must co-occur (\"--id-contains-all abc,xyz\" finds every op whose UUID contains BOTH abc AND xyz in any order/position, e.g. abc-123-xyz). Whitespace around commas is trimmed. Mutually exclusive with --id-contains, --not-id-contains, --id-contains-any, and --not-id-contains-any.',\n )\n .option(\n '--not-id-contains-all <substrings>',\n 'Exclude ops whose id contains EVERY substring in this comma-separated list (case-sensitive — UUIDs are case-sensitive, mirrors --not-id-contains and --not-id-contains-any). Plural AND-negation of --id-contains — useful audit filter (\"--not-id-contains-all abc,xyz\" excludes ONLY ops whose UUID contains BOTH abc and xyz, keeping ops with just one keyword or neither). Whitespace around commas is trimmed. Mutually exclusive with --id-contains, --not-id-contains, --id-contains-any, --not-id-contains-any, and --id-contains-all.',\n )\n .option(\n '--id-regex <pattern>',\n \"Filter to ops whose id matches this JavaScript regular expression (**case-sensitive** — UUIDs are case-sensitive, mirrors --id-contains and the id-contains-any/all family). Power-user complement to --id-contains-any for full pattern matching on the ID axis: anchors (^/$), character classes ([0-9a-f]/\\\\d/\\\\w), quantifiers, groups, alternation (foo|bar), lookaround. Useful for UUID-shape audits (\\\"--id-regex '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'\\\" finds every op with a strictly-formatted v4 UUID — the canonical RFC-4122 shape check). Invalid regex syntax refuses with exit 1. Ops with no id are excluded (a missing id doesn't match anything — symmetric with --id-contains-any). Mutually exclusive with --id-contains, --not-id-contains, --id-contains-any, --not-id-contains-any, --id-contains-all, and --not-id-contains-all.\",\n )\n .option(\n '--not-id-regex <pattern>',\n \"Exclude ops whose id matches this JavaScript regular expression (**case-sensitive** — UUIDs are case-sensitive, mirrors --not-id-contains and the id-contains-any/all family). Power-user negation complement to --not-id-contains-any for full pattern-based exclusion on the ID axis: anchors (^/$), character classes, quantifiers, groups, alternation, lookaround. Useful audit filter (\\\"--not-id-regex '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'\\\" finds every op whose id is NOT a strictly-formatted v4 UUID — the non-canonical id audit, surfaces ops with legacy/test-shaped ids). Invalid regex syntax refuses with exit 1. Ops with no id are KEPT (a missing id doesn't match anything, so it isn't excluded — symmetric with --not-id-contains-any). Mutually exclusive with --id-contains, --not-id-contains, --id-contains-any, --not-id-contains-any, --id-contains-all, --not-id-contains-all, and --id-regex.\",\n )\n .option(\n '--note-contains <text>',\n 'Filter to ops whose note contains this substring (case-insensitive). Composes with other filters as intersection. Useful for finding ops tagged with a project/ticket reference.',\n )\n .option(\n '--not-note-contains <text>',\n 'Exclude ops whose note contains this substring (case-insensitive). Negation of --note-contains — useful audit filter (\"show me ops not yet tagged with PROJ-1\"). Ops with no note are KEPT (a missing note doesn\\'t contain anything, so it isn\\'t excluded). To exclude un-noted ops too, compose with --has-note. Mutually exclusive with --note-contains.',\n )\n .option(\n '--note-contains-any <texts>',\n 'Filter to ops whose note contains ANY substring in this comma-separated list (case-insensitive). Plural OR-semantics form of --note-contains — useful for multi-keyword audits (\"--note-contains-any PROJ-,JIRA-,TKT-\" finds every refactor whose note mentions a ticket from any of three namespaces anywhere in the text, not just at the start). Whitespace around commas is trimmed. Ops with no note are excluded (a missing note doesn\\'t contain anything). Mutually exclusive with --note-contains and --not-note-contains.',\n )\n .option(\n '--not-note-contains-any <texts>',\n 'Exclude ops whose note contains ANY substring in this comma-separated list (case-insensitive). Plural OR-negation of --note-contains — useful audit filter (\"--not-note-contains-any PROJ-,JIRA-,TKT- finds every refactor whose note avoids any of three keywords\"). Whitespace around commas is trimmed. Ops with no note are KEPT (a missing note doesn\\'t contain anything). To exclude un-noted ops too, compose with --has-note. Mutually exclusive with --note-contains, --not-note-contains, and --note-contains-any.',\n )\n .option(\n '--note-contains-all <texts>',\n 'Filter to ops whose note contains EVERY substring in this comma-separated list (case-insensitive). Plural AND-semantics form of --note-contains — useful for narrow audits where multiple keywords must co-occur (\"--note-contains-all hotfix,rollback\" finds every refactor whose note mentions BOTH hotfix and rollback anywhere in the text). Whitespace around commas is trimmed. Ops with no note are excluded (a missing note doesn\\'t contain anything). Mutually exclusive with --note-contains, --not-note-contains, --note-contains-any, and --not-note-contains-any.',\n )\n .option(\n '--not-note-contains-all <texts>',\n 'Exclude ops whose note contains EVERY substring in this comma-separated list (case-insensitive). Plural AND-negation of --note-contains — useful audit filter (\"--not-note-contains-all hotfix,rollback\" excludes only refactors whose note mentions BOTH hotfix and rollback, keeping ops that mention just one or neither). Whitespace around commas is trimmed. Ops with no note are KEPT (a missing note doesn\\'t contain anything). To exclude un-noted ops too, compose with --has-note. Mutually exclusive with --note-contains, --not-note-contains, --note-contains-any, --not-note-contains-any, and --note-contains-all.',\n )\n .option(\n '--note-regex <pattern>',\n \"Filter to ops whose note matches this JavaScript regular expression (case-insensitive — mirrors --note-contains*). Power-user complement to --note-contains for full pattern matching: anchors (^/$), character classes ([A-Z]/\\\\d/\\\\w/\\\\s), quantifiers (+/*/?/{n,m}), groups, alternation (foo|bar), and lookaround. Useful for compound audits (\\\"--note-regex '^(PROJ|JIRA)-[0-9]+'\\\" finds every refactor whose note begins with a ticket reference from one of two namespaces). Invalid regex syntax refuses with exit 1. Ops with no note are excluded (a missing note doesn't match anything). Mutually exclusive with --note-contains, --not-note-contains, --note-contains-any, --not-note-contains-any, --note-contains-all, and --not-note-contains-all.\",\n )\n .option(\n '--not-note-regex <pattern>',\n \"Exclude ops whose note matches this JavaScript regular expression (case-insensitive — mirrors --note-contains*). Power-user negation complement to --not-note-contains for full pattern-based exclusion: anchors (^/$), character classes, quantifiers, groups, alternation, lookaround. Useful audit filter (\\\"--not-note-regex '^(PROJ|JIRA)-[0-9]+'\\\" finds every refactor whose note does NOT begin with a ticket reference from one of two namespaces — the un-ticketed work). Invalid regex syntax refuses with exit 1. Ops with no note are KEPT (a missing note doesn't match anything, so it isn't excluded — symmetric with --not-note-contains). To exclude un-noted ops too, compose with --has-note. Mutually exclusive with --note-contains, --not-note-contains, --note-contains-any, --not-note-contains-any, --note-contains-all, --not-note-contains-all, and --note-regex.\",\n )\n .option(\n '--note-prefix <prefix>',\n 'Filter to ops whose note starts with this prefix (case-insensitive). Composes with other filters as intersection. Useful for ticket-prefix audits (\"--note-prefix PROJ-\" finds every op tagged with a PROJ-N ticket).',\n )\n .option(\n '--not-note-prefix <prefix>',\n 'Exclude ops whose note starts with this prefix (case-insensitive). Negation of --note-prefix — useful audit filter (\"--not-note-prefix PROJ-\" finds every op tagged outside the PROJ- ticket namespace). Ops with no note are KEPT (a missing note doesn\\'t start with anything). To exclude un-noted ops too, compose with --has-note. Mutually exclusive with --note-prefix.',\n )\n .option(\n '--note-prefixes <prefixes>',\n 'Filter to ops whose note starts with any prefix in this comma-separated list (case-insensitive). Plural OR-semantics form of --note-prefix — useful for multi-ticket-namespace audits (\"--note-prefixes PROJ-,JIRA-,TKT-\" finds every refactor tagged with a ticket from any of three namespaces in a single pass). Whitespace around commas is trimmed. Ops with no note are excluded (a missing note doesn\\'t start with anything). Mutually exclusive with --note-prefix and --not-note-prefix.',\n )\n .option(\n '--not-note-prefixes <prefixes>',\n 'Exclude ops whose note starts with any prefix in this comma-separated list (case-insensitive). Plural OR-negation of --note-prefix — useful audit filter (\"--not-note-prefixes PROJ-,JIRA-,TKT-\" finds every refactor tagged outside any of three ticket namespaces in a single pass). Whitespace around commas is trimmed. Ops with no note are KEPT (a missing note doesn\\'t start with anything). To exclude un-noted ops too, compose with --has-note. Mutually exclusive with --note-prefix, --not-note-prefix, and --note-prefixes.',\n )\n .option(\n '--note-suffix <suffix>',\n 'Filter to ops whose note ends with this suffix (case-insensitive). Mirror of --note-prefix. Composes with other filters as intersection. Useful for \"find ops tagged with a specific trailing label\" workflows (\"--note-suffix [reviewed]\").',\n )\n .option(\n '--not-note-suffix <suffix>',\n 'Exclude ops whose note ends with this suffix (case-insensitive). Negation of --note-suffix — useful audit filter (\"--not-note-suffix [reviewed]\" finds every op still missing the reviewed label). Ops with no note are KEPT (a missing note doesn\\'t end with anything). To exclude un-noted ops too, compose with --has-note. Mutually exclusive with --note-suffix.',\n )\n .option(\n '--note-suffixes <suffixes>',\n 'Filter to ops whose note ends with any suffix in this comma-separated list (case-insensitive). Plural OR-semantics form of --note-suffix — useful for multi-label audits (\"--note-suffixes [reviewed],[approved],[merged]\" finds every refactor tagged with any trailing approval label in a single pass). Whitespace around commas is trimmed. Ops with no note are excluded (a missing note doesn\\'t end with anything). Mutually exclusive with --note-suffix and --not-note-suffix.',\n )\n .option(\n '--not-note-suffixes <suffixes>',\n 'Exclude ops whose note ends with any suffix in this comma-separated list (case-insensitive). Plural OR-negation of --note-suffix — useful audit filter (\"--not-note-suffixes [reviewed],[approved],[merged]\" finds every refactor still missing any of three approval labels in a single pass). Whitespace around commas is trimmed. Ops with no note are KEPT (a missing note doesn\\'t end with anything). To exclude un-noted ops too, compose with --has-note. Mutually exclusive with --note-suffix, --not-note-suffix, and --note-suffixes.',\n )\n .option(\n '--note-exact <text>',\n 'Filter to ops whose note equals this text (case-insensitive). Precision lookup — useful when many ops share a common note prefix/suffix and you need the one with the exact note value. Composes with other filters as intersection.',\n )\n .option(\n '--notes <texts>',\n 'Filter to ops whose note equals any text in this comma-separated list (case-insensitive). Plural form of --note-exact — useful audit filter (\"--notes PROJ-1,PROJ-2,PROJ-3\" finds every refactor tagged with any of those notes in a single pass). Whitespace around commas is trimmed (notes with embedded commas can\\'t use this; use --note-exact for those). Mutually exclusive with --note-exact and --not-note-exact.',\n )\n .option(\n '--not-notes <texts>',\n 'Exclude ops whose note equals any text in this comma-separated list (case-insensitive). Plural negation of --note-exact — useful audit filter (\"--not-notes PROJ-1,PROJ-2,PROJ-3\" finds every refactor except those tagged with the named notes in a single pass). Whitespace around commas is trimmed. Ops with no note are KEPT (a missing note doesn\\'t equal anything; compose with --has-note to exclude un-noted ops too). Mutually exclusive with --note-exact, --not-note-exact, and --notes.',\n )\n .option(\n '--not-note-exact <text>',\n 'Exclude ops whose note equals this text (case-insensitive). Negation of --note-exact — useful precision audit filter (\"--not-note-exact \\'PROJ-1\\'\" finds every op except the one with that exact note, without false-matching \"PROJ-1 followup\" / \"PROJ-1 part 2\"). Ops with no note are KEPT (a missing note doesn\\'t equal anything). Mutually exclusive with --note-exact.',\n )\n .option(\n '--object-type <type>',\n 'Filter to ops whose target object.objectType matches this kind (TABLE, VIEW, MATERIALIZED_VIEW, …); case-insensitive. Composes with other filters as intersection. Pairs with the --object-type flag on rename-object/move-object recordings.',\n )\n .option(\n '--not-object-type <type>',\n 'Exclude ops whose target object.objectType matches this kind. Negation of --object-type — useful audit filter (\"show every non-TABLE refactor\"). Case-insensitive. Mutually exclusive with --object-type.',\n )\n .option(\n '--object-types <types>',\n 'Filter to ops whose target object.objectType is in this comma-separated list (case-insensitive). Plural form of --object-type — useful audit filter (\"--object-types TABLE,VIEW\" finds every refactor on a non-procedural object in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --object-type and --not-object-type.',\n )\n .option(\n '--not-object-types <types>',\n 'Exclude ops whose target object.objectType is in this comma-separated list (case-insensitive). Plural negation of --object-type — useful audit filter (\"--not-object-types PROCEDURE,FUNCTION\" finds every non-procedural refactor in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --object-type, --not-object-type, and --object-types.',\n )\n .option(\n '--name <substring>',\n 'Filter to ops whose target object.name contains this substring (case-insensitive). Composes with other filters as intersection. Useful for \"what happened to the orders table?\" style audits.',\n )\n .option(\n '--not-name <substring>',\n 'Exclude ops whose target object.name contains this substring (case-insensitive). Negation of --name — useful audit filter (\"show me every refactor that isn\\'t on the orders table\"). Mutually exclusive with --name.',\n )\n .option(\n '--name-contains-any <substrings>',\n 'Filter to ops whose target object.name contains ANY substring in this comma-separated list (case-insensitive). Plural OR-semantics form of --name — useful for multi-keyword audits (\"--name-contains-any orders,invoices,customers\" finds every refactor on a table whose name embeds any of three keywords in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --name and --not-name.',\n )\n .option(\n '--not-name-contains-any <substrings>',\n 'Exclude ops whose target object.name contains ANY substring in this comma-separated list (case-insensitive). Plural OR-negation of --name — useful audit filter (\"--not-name-contains-any orders,invoices,customers\" finds every refactor on a table whose name doesn\\'t embed any of three keywords in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --name, --not-name, and --name-contains-any.',\n )\n .option(\n '--name-contains-all <substrings>',\n 'Filter to ops whose target object.name contains EVERY substring in this comma-separated list (case-insensitive). Plural AND-semantics form of --name — useful for narrow audits where multiple keywords must co-occur in the table name (\"--name-contains-all fact,daily\" finds every refactor on a table whose name contains BOTH fact and daily, e.g. FACT_ORDERS_DAILY). Whitespace around commas is trimmed. Mutually exclusive with --name, --not-name, --name-contains-any, and --not-name-contains-any.',\n )\n .option(\n '--not-name-contains-all <substrings>',\n 'Exclude ops whose target object.name contains EVERY substring in this comma-separated list (case-insensitive). Plural AND-negation of --name — useful audit filter (\"--not-name-contains-all fact,daily\" excludes ONLY refactors on tables whose name contains BOTH fact and daily, keeping ops on tables with just one keyword or neither). Whitespace around commas is trimmed. Mutually exclusive with --name, --not-name, --name-contains-any, --not-name-contains-any, and --name-contains-all.',\n )\n .option(\n '--name-regex <pattern>',\n \"Filter to ops whose target object.name matches this JavaScript regular expression (case-insensitive — mirrors --name-contains-any/all). Power-user complement to --name-contains-any for full pattern matching: anchors (^/$), character classes ([A-Z]/\\\\d/\\\\w/\\\\s), quantifiers (+/*/?/{n,m}), groups, alternation (foo|bar), word-boundary (\\\\b), lookaround. Useful for naming-convention audits (\\\"--name-regex '^(stg|raw|fact)_[a-z]+_v[0-9]+$'\\\" finds every versioned table on staging/raw/fact namespaces in a single pass — neither --name-prefixes nor --name-contains-any can express the trailing version anchor). Invalid regex syntax refuses with exit 1. Ops with no object.name are excluded (a missing name doesn't match anything). Mutually exclusive with --name, --not-name, --name-contains-any, --not-name-contains-any, --name-contains-all, and --not-name-contains-all.\",\n )\n .option(\n '--not-name-regex <pattern>',\n \"Exclude ops whose target object.name matches this JavaScript regular expression (case-insensitive — mirrors --name-contains-any/all). Power-user negation complement to --not-name-contains-any for full pattern-based exclusion: anchors (^/$), character classes, quantifiers, groups, alternation, lookaround. Useful audit filter (\\\"--not-name-regex '^(stg|raw)_'\\\" finds every refactor on a non-staging non-raw table — the production-tier audit). Invalid regex syntax refuses with exit 1. Ops with no object.name are KEPT (a missing name doesn't match anything, so it isn't excluded — symmetric with --not-name-contains-any). Mutually exclusive with --name, --not-name, --name-contains-any, --not-name-contains-any, --name-contains-all, --not-name-contains-all, and --name-regex.\",\n )\n .option(\n '--name-prefix <prefix>',\n 'Filter to ops whose target object.name starts with this prefix (case-insensitive). Composes with other filters as intersection. Useful for naming-convention audits (\"--name-prefix stg_\" finds every staging-table refactor).',\n )\n .option(\n '--name-prefixes <prefixes>',\n 'Filter to ops whose target object.name starts with any prefix in this comma-separated list (case-insensitive). Plural OR-semantics form of --name-prefix — useful for multi-namespace audits (\"--name-prefixes stg_,raw_,fact_\" finds every refactor on a staging, raw, or fact table in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --name-prefix and --not-name-prefix.',\n )\n .option(\n '--not-name-prefixes <prefixes>',\n 'Exclude ops whose target object.name starts with any prefix in this comma-separated list (case-insensitive). Plural OR-negation of --name-prefix — useful audit filter (\"--not-name-prefixes stg_,raw_,fact_\" finds every refactor except those on staging, raw, or fact tables in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --name-prefix, --not-name-prefix, and --name-prefixes.',\n )\n .option(\n '--not-name-prefix <prefix>',\n 'Exclude ops whose target object.name starts with this prefix (case-insensitive). Negation of --name-prefix — useful audit filter (\"--not-name-prefix stg_\" finds every non-staging refactor). Mutually exclusive with --name-prefix.',\n )\n .option(\n '--name-suffix <suffix>',\n 'Filter to ops whose target object.name ends with this suffix (case-insensitive). Mirror of --name-prefix. Composes with other filters as intersection. Useful for finding versioned-table refactors (\"--name-suffix _v2\").',\n )\n .option(\n '--name-suffixes <suffixes>',\n 'Filter to ops whose target object.name ends with any suffix in this comma-separated list (case-insensitive). Plural OR-semantics form of --name-suffix — useful for multi-version audits (\"--name-suffixes _v1,_v2,_v3\" finds every refactor on any versioned table in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --name-suffix and --not-name-suffix.',\n )\n .option(\n '--not-name-suffixes <suffixes>',\n 'Exclude ops whose target object.name ends with any suffix in this comma-separated list (case-insensitive). Plural OR-negation of --name-suffix — useful audit filter (\"--not-name-suffixes _v1,_v2,_v3\" finds every refactor except those on versioned tables in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --name-suffix, --not-name-suffix, and --name-suffixes.',\n )\n .option(\n '--not-name-suffix <suffix>',\n 'Exclude ops whose target object.name ends with this suffix (case-insensitive). Negation of --name-suffix — useful audit filter (\"--not-name-suffix _v2\" finds every non-v2 refactor). Mutually exclusive with --name-suffix.',\n )\n .option(\n '--name-exact <name>',\n 'Filter to ops whose target object.name equals this name (case-insensitive). Precision lookup — useful for short or common names where --name (substring), --name-prefix, --name-suffix would all match too many ops. Composes with other filters as intersection.',\n )\n .option(\n '--names <names>',\n 'Filter to ops whose target object.name equals any name in this comma-separated list (case-insensitive). Plural form of --name-exact — useful audit filter (\"--names orders,invoices,sales\" finds every refactor on any of those tables in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --name-exact and --not-name-exact.',\n )\n .option(\n '--not-names <names>',\n 'Exclude ops whose target object.name equals any name in this comma-separated list (case-insensitive). Plural negation of --name-exact — useful audit filter (\"--not-names orders,invoices,sales\" finds every refactor except those on the named tables in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --name-exact, --not-name-exact, and --names.',\n )\n .option(\n '--not-name-exact <name>',\n 'Exclude ops whose target object.name equals this name (case-insensitive). Negation of --name-exact — useful precision audit filter (\"--not-name-exact orders\" finds every refactor except the orders table without false-matching orders_v2 / stg_orders / etc). Mutually exclusive with --name-exact.',\n )\n .option(\n '--schema <substring>',\n 'Filter to ops whose target object.schema contains this substring (case-insensitive). Composes with other filters as intersection. Useful for \"show me all the refactors on schema marketing.\"',\n )\n .option(\n '--not-schema <substring>',\n 'Exclude ops whose target object.schema contains this substring (case-insensitive). Negation of --schema — useful audit filter (\"show every refactor that isn\\'t on schema marketing\"). Mutually exclusive with --schema.',\n )\n .option(\n '--schema-contains-any <substrings>',\n 'Filter to ops whose target object.schema contains ANY substring in this comma-separated list (case-insensitive). Plural OR-semantics form of --schema — useful for multi-namespace audits (\"--schema-contains-any marketing,finance,ops\" finds every refactor on a schema whose name embeds any of three keywords in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --schema and --not-schema.',\n )\n .option(\n '--not-schema-contains-any <substrings>',\n 'Exclude ops whose target object.schema contains ANY substring in this comma-separated list (case-insensitive). Plural OR-negation of --schema — useful audit filter (\"--not-schema-contains-any marketing,finance,ops\" finds every refactor on a schema whose name doesn\\'t embed any of three keywords in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --schema, --not-schema, and --schema-contains-any.',\n )\n .option(\n '--schema-contains-all <substrings>',\n 'Filter to ops whose target object.schema contains EVERY substring in this comma-separated list (case-insensitive). Plural AND-semantics form of --schema — useful for narrow audits where multiple keywords must co-occur in the schema name (\"--schema-contains-all finance,prod\" finds every refactor on a schema whose name contains BOTH finance and prod, e.g. finance_prod). Whitespace around commas is trimmed. Mutually exclusive with --schema, --not-schema, --schema-contains-any, and --not-schema-contains-any.',\n )\n .option(\n '--not-schema-contains-all <substrings>',\n 'Exclude ops whose target object.schema contains EVERY substring in this comma-separated list (case-insensitive). Plural AND-negation of --schema — useful audit filter (\"--not-schema-contains-all finance,prod\" excludes ONLY refactors on schemas whose name contains BOTH finance and prod, keeping schemas with just one keyword or neither). Whitespace around commas is trimmed. Mutually exclusive with --schema, --not-schema, --schema-contains-any, --not-schema-contains-any, and --schema-contains-all.',\n )\n .option(\n '--schema-regex <pattern>',\n \"Filter to ops whose target object.schema matches this JavaScript regular expression (case-insensitive — mirrors --schema-contains-any/all). Power-user complement to --schema-contains-any for full pattern matching on the SCHEMA axis: anchors (^/$), character classes, quantifiers, groups, alternation (foo|bar), lookaround. Useful for schema-naming-convention audits (\\\"--schema-regex '^(FINANCE|HR)_(PROD|STG)$'\\\" finds every refactor on a finance-or-HR production-or-staging schema in a single pass — the alternation matrix that --schema-prefixes cannot express). Invalid regex syntax refuses with exit 1. Ops with no object.schema are excluded (a missing schema doesn't match anything). Mutually exclusive with --schema, --not-schema, --schema-contains-any, --not-schema-contains-any, --schema-contains-all, and --not-schema-contains-all.\",\n )\n .option(\n '--not-schema-regex <pattern>',\n \"Exclude ops whose target object.schema matches this JavaScript regular expression (case-insensitive — mirrors --schema-contains-any/all). Power-user negation complement to --not-schema-contains-any for full pattern-based exclusion: anchors (^/$), character classes, quantifiers, groups, alternation, lookaround. Useful audit filter (\\\"--not-schema-regex '_(STG|DEV)$'\\\" finds every refactor on a non-staging non-dev schema — the production-only audit). Invalid regex syntax refuses with exit 1. Ops with no object.schema are KEPT (a missing schema doesn't match anything, so it isn't excluded — symmetric with --not-schema-contains-any). Mutually exclusive with --schema, --not-schema, --schema-contains-any, --not-schema-contains-any, --schema-contains-all, --not-schema-contains-all, and --schema-regex.\",\n )\n .option(\n '--schema-prefix <prefix>',\n 'Filter to ops whose target object.schema starts with this prefix (case-insensitive). Composes with other filters as intersection. Useful for schema-namespace audits (\"--schema-prefix stg_\" finds every refactor on staging schemas while excluding mid-name *stg_* matches that the --schema substring filter would falsely include).',\n )\n .option(\n '--not-schema-prefix <prefix>',\n 'Exclude ops whose target object.schema starts with this prefix (case-insensitive). Negation of --schema-prefix — useful audit filter (\"--not-schema-prefix stg_\" finds every non-staging refactor without false-matching mid-name *stg_* schemas). Mutually exclusive with --schema-prefix.',\n )\n .option(\n '--schema-prefixes <prefixes>',\n 'Filter to ops whose target object.schema starts with any prefix in this comma-separated list (case-insensitive). Plural OR-semantics form of --schema-prefix — useful for multi-namespace audits (\"--schema-prefixes stg_,raw_,fact_\" finds every refactor on staging, raw, or fact schemas in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --schema-prefix and --not-schema-prefix.',\n )\n .option(\n '--not-schema-prefixes <prefixes>',\n 'Exclude ops whose target object.schema starts with any prefix in this comma-separated list (case-insensitive). Plural OR-negation of --schema-prefix — useful audit filter (\"--not-schema-prefixes stg_,raw_,fact_\" finds every refactor except those on staging, raw, or fact schemas in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --schema-prefix, --not-schema-prefix, and --schema-prefixes.',\n )\n .option(\n '--schema-suffix <suffix>',\n 'Filter to ops whose target object.schema ends with this suffix (case-insensitive). Mirror of --schema-prefix. Composes with other filters as intersection. Useful for trailing-namespace audits (\"--schema-suffix _prod\" finds every refactor on production schemas while excluding mid-name _prod_ matches).',\n )\n .option(\n '--not-schema-suffix <suffix>',\n 'Exclude ops whose target object.schema ends with this suffix (case-insensitive). Negation of --schema-suffix — useful audit filter (\"--not-schema-suffix _prod\" finds every refactor on non-production schemas). Mutually exclusive with --schema-suffix.',\n )\n .option(\n '--schema-suffixes <suffixes>',\n 'Filter to ops whose target object.schema ends with any suffix in this comma-separated list (case-insensitive). Plural OR-semantics form of --schema-suffix — useful for trailing-namespace audits (\"--schema-suffixes _prod,_stg,_dev\" finds every refactor on production, staging, or dev schemas in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --schema-suffix and --not-schema-suffix.',\n )\n .option(\n '--not-schema-suffixes <suffixes>',\n 'Exclude ops whose target object.schema ends with any suffix in this comma-separated list (case-insensitive). Plural OR-negation of --schema-suffix — useful audit filter (\"--not-schema-suffixes _prod,_stg,_dev\" finds every refactor except those on production, staging, or dev schemas in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --schema-suffix, --not-schema-suffix, and --schema-suffixes.',\n )\n .option(\n '--schema-exact <name>',\n 'Filter to ops whose target object.schema equals this name (case-insensitive). Precision lookup — useful for short or common schema names where --schema (substring), --schema-prefix, --schema-suffix would all match too many ops. Composes with other filters as intersection.',\n )\n .option(\n '--schemas <names>',\n 'Filter to ops whose target object.schema equals any name in this comma-separated list (case-insensitive). Plural form of --schema-exact — useful audit filter (\"--schemas marketing,finance,ops\" finds every refactor on any of those schemas in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --schema-exact and --not-schema-exact.',\n )\n .option(\n '--not-schemas <names>',\n 'Exclude ops whose target object.schema equals any name in this comma-separated list (case-insensitive). Plural negation of --schema-exact — useful audit filter (\"--not-schemas marketing,finance,ops\" finds every refactor except those on the named schemas in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --schema-exact, --not-schema-exact, and --schemas.',\n )\n .option(\n '--not-schema-exact <name>',\n 'Exclude ops whose target object.schema equals this name (case-insensitive). Negation of --schema-exact — useful precision audit filter (\"--not-schema-exact marketing\" finds every refactor outside the exact marketing schema without false-matching marketing_stg / raw_marketing). Mutually exclusive with --schema-exact.',\n )\n .option(\n '--database <substring>',\n 'Filter to ops whose target object.database contains this substring (case-insensitive). Composes with other filters as intersection. Useful for \"show me all the refactors on the analytics_prod catalog.\" (Refactor log records the top container as `database` even though the Databricks term is catalog.)',\n )\n .option(\n '--not-database <substring>',\n 'Exclude ops whose target object.database contains this substring (case-insensitive). Negation of --database — useful audit filter (\"show every refactor that isn\\'t on catalog analytics_prod\"). Mutually exclusive with --database. (Refactor log records the top container as `database` even though the Databricks term is catalog.)',\n )\n .option(\n '--database-contains-any <substrings>',\n 'Filter to ops whose target object.database contains ANY substring in this comma-separated list (case-insensitive). Plural OR-semantics form of --database — useful for multi-catalog audits (\"--database-contains-any analytics,raw,stg\" finds every refactor on a catalog whose name embeds any of three keywords in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --database and --not-database. (Refactor log records the top container as `database` even though the Databricks term is catalog.)',\n )\n .option(\n '--not-database-contains-any <substrings>',\n 'Exclude ops whose target object.database contains ANY substring in this comma-separated list (case-insensitive). Plural OR-negation of --database — useful audit filter (\"--not-database-contains-any analytics,raw,stg\" finds every refactor on a catalog whose name doesn\\'t embed any of three keywords in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --database, --not-database, and --database-contains-any. (Refactor log records the top container as `database` even though the Databricks term is catalog.)',\n )\n .option(\n '--database-contains-all <substrings>',\n 'Filter to ops whose target object.database contains EVERY substring in this comma-separated list (case-insensitive). Plural AND-semantics form of --database — useful for narrow audits where multiple keywords must co-occur in the catalog name (\"--database-contains-all analytics,prod\" finds every refactor on a catalog whose name contains BOTH analytics and prod, e.g. analytics_prod). Whitespace around commas is trimmed. Mutually exclusive with --database, --not-database, --database-contains-any, and --not-database-contains-any. (Refactor log records the top container as `database` even though the Databricks term is catalog.)',\n )\n .option(\n '--not-database-contains-all <substrings>',\n 'Exclude ops whose target object.database contains EVERY substring in this comma-separated list (case-insensitive). Plural AND-negation of --database — useful audit filter (\"--not-database-contains-all analytics,prod\" excludes ONLY refactors on catalogs whose name contains BOTH analytics and prod, keeping catalogs with just one keyword or neither). Whitespace around commas is trimmed. Mutually exclusive with --database, --not-database, --database-contains-any, --not-database-contains-any, and --database-contains-all. (Refactor log records the top container as `database` even though the Databricks term is catalog.)',\n )\n .option(\n '--database-regex <pattern>',\n \"Filter to ops whose target object.database matches this JavaScript regular expression (case-insensitive — mirrors --database-contains-any/all). Power-user complement to --database-contains-any for full pattern matching on the DATABASE axis: anchors (^/$), character classes, quantifiers, groups, alternation (foo|bar), lookaround. Useful for catalog-naming-convention audits across multi-tenant deployments (\\\"--database-regex '^(ANALYTICS|REPORTING)_(PROD|STG)$'\\\" finds every refactor on an analytics-or-reporting production-or-staging catalog — the FQN tier matrix). Invalid regex syntax refuses with exit 1. Ops with no object.database are excluded (a missing database doesn't match anything). Mutually exclusive with --database, --not-database, --database-contains-any, --not-database-contains-any, --database-contains-all, and --not-database-contains-all.\",\n )\n .option(\n '--not-database-regex <pattern>',\n \"Exclude ops whose target object.database matches this JavaScript regular expression (case-insensitive — mirrors --database-contains-any/all). Power-user negation complement to --not-database-contains-any for full pattern-based exclusion: anchors (^/$), character classes, quantifiers, groups, alternation, lookaround. Useful audit filter (\\\"--not-database-regex '_(STG|DEV|QA)$'\\\" finds every refactor on a non-staging non-dev non-qa catalog — the production-only multi-tenant audit). Invalid regex syntax refuses with exit 1. Ops with no object.database are KEPT (a missing database doesn't match anything, so it isn't excluded — symmetric with --not-database-contains-any). Mutually exclusive with --database, --not-database, --database-contains-any, --not-database-contains-any, --database-contains-all, --not-database-contains-all, and --database-regex.\",\n )\n .option(\n '--database-prefix <prefix>',\n 'Filter to ops whose target object.database starts with this prefix (case-insensitive). Composes with other filters as intersection. Useful for catalog-tier audits (\"--database-prefix analytics_\" finds every refactor on analytics catalogs while excluding mid-name *analytics_* matches that the --database substring filter would falsely include). (Refactor log records the top container as `database` even though the Databricks term is catalog.)',\n )\n .option(\n '--not-database-prefix <prefix>',\n 'Exclude ops whose target object.database starts with this prefix (case-insensitive). Negation of --database-prefix — useful audit filter (\"--not-database-prefix analytics_\" finds every refactor on non-analytics catalogs without false-matching mid-name *analytics_* catalogs). Mutually exclusive with --database-prefix. (Refactor log records the top container as `database` even though the Databricks term is catalog.)',\n )\n .option(\n '--database-prefixes <prefixes>',\n 'Filter to ops whose target object.database starts with any prefix in this comma-separated list (case-insensitive). Plural OR-semantics form of --database-prefix — useful for multi-tier audits (\"--database-prefixes analytics_,raw_,stg_\" finds every refactor on analytics, raw, or staging catalogs in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --database-prefix and --not-database-prefix. (Refactor log records the top container as `database` even though the Databricks term is catalog.)',\n )\n .option(\n '--not-database-prefixes <prefixes>',\n 'Exclude ops whose target object.database starts with any prefix in this comma-separated list (case-insensitive). Plural OR-negation of --database-prefix — useful audit filter (\"--not-database-prefixes analytics_,raw_,stg_\" finds every refactor except those on analytics, raw, or staging catalogs in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --database-prefix, --not-database-prefix, and --database-prefixes. (Refactor log records the top container as `database` even though the Databricks term is catalog.)',\n )\n .option(\n '--database-suffix <suffix>',\n 'Filter to ops whose target object.database ends with this suffix (case-insensitive). Mirror of --database-prefix. Composes with other filters as intersection. Useful for environment-suffix audits (\"--database-suffix _prod\" finds every refactor on production catalogs while excluding leading prod_* matches).',\n )\n .option(\n '--not-database-suffix <suffix>',\n 'Exclude ops whose target object.database ends with this suffix (case-insensitive). Negation of --database-suffix — useful audit filter (\"--not-database-suffix _prod\" finds every refactor on non-production catalogs). Mutually exclusive with --database-suffix.',\n )\n .option(\n '--database-suffixes <suffixes>',\n 'Filter to ops whose target object.database ends with any suffix in this comma-separated list (case-insensitive). Plural OR-semantics form of --database-suffix — useful for multi-environment audits (\"--database-suffixes _prod,_stg,_dev\" finds every refactor on production, staging, or dev catalogs in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --database-suffix and --not-database-suffix.',\n )\n .option(\n '--not-database-suffixes <suffixes>',\n 'Exclude ops whose target object.database ends with any suffix in this comma-separated list (case-insensitive). Plural OR-negation of --database-suffix — useful audit filter (\"--not-database-suffixes _prod,_stg,_dev\" finds every refactor except those on production, staging, or dev catalogs in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --database-suffix, --not-database-suffix, and --database-suffixes.',\n )\n .option(\n '--database-exact <name>',\n 'Filter to ops whose target object.database equals this name (case-insensitive). Precision lookup — useful for short or common catalog names where --database (substring), --database-prefix, --database-suffix would all match too many ops. Composes with other filters as intersection.',\n )\n .option(\n '--databases <names>',\n 'Filter to ops whose target object.database equals any name in this comma-separated list (case-insensitive). Plural form of --database-exact — useful audit filter (\"--databases analytics,raw,staging\" finds every refactor on any of those catalogs in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --database-exact and --not-database-exact. (Refactor log records the top container as `database` even though the Databricks term is catalog.)',\n )\n .option(\n '--not-databases <names>',\n 'Exclude ops whose target object.database equals any name in this comma-separated list (case-insensitive). Plural negation of --database-exact — useful audit filter (\"--not-databases analytics,raw,staging\" finds every refactor except those on the named catalogs in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --database-exact, --not-database-exact, and --databases. (Refactor log records the top container as `database` even though the Databricks term is catalog.)',\n )\n .option(\n '--not-database-exact <name>',\n 'Exclude ops whose target object.database equals this name (case-insensitive). Negation of --database-exact — useful precision audit filter (\"--not-database-exact analytics\" finds every refactor outside the exact analytics catalog without false-matching analytics_prod / audit_analytics). Mutually exclusive with --database-exact. (Refactor log records the top container as `database` even though the Databricks term is catalog.)',\n )\n .option(\n '--name-min-length <n>',\n 'Filter to ops whose target object.name length is >= n (length is a count, not a char-set concern). Useful for naming-convention audits (\"--name-min-length 30\" finds refactors on tables whose name is suspiciously long — likely candidates for shortening). n must be a non-negative integer; non-numeric or negative refuses with exit 1. Ops with no object.name (rare in practice — name is always set per Op contract) are excluded (a missing name has no length). Opens a new LENGTH sub-arc on the refactor-list filter surface, mirroring the contains-any (iters 291-300), contains-all (iters 301-310), regex (iters 311-320), and HAS/MISSING-IDENT (iters 321-324) sub-arcs. First flag of 10-pair sub-arc covering all 5 axes (name, schema, database, note, id) × 2 directions (min, max). Composes with --name-max-length for closed-range length filters (e.g. \"8 <= length <= 32\"). Composes with other filters as intersection.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--name-max-length <n>',\n 'Filter to ops whose target object.name length is <= n. Useful for naming-convention audits (\"--name-max-length 10\" finds refactors on tables with short/abbreviated names — candidates for expansion to a more descriptive form). n must be a non-negative integer; non-numeric or negative refuses with exit 1. Ops with no object.name are excluded (a missing name has no length, so it can\\'t satisfy a max bound — symmetric with --name-min-length). CLOSES the name length pair, 1/5 pair of the LENGTH sub-arc opened iter 325. Composes with --name-min-length for closed-range queries (e.g. \"--name-min-length 8 --name-max-length 32\" enforces an 8-32 char name policy). Refuses if min > max when both are set (range is empty by definition).',\n (v) => parseInt(v, 10),\n )\n .option(\n '--schema-min-length <n>',\n 'Filter to ops whose target object.schema length is >= n. Useful for naming-convention audits on the schema axis (\"--schema-min-length 20\" finds refactors on schemas with suspiciously-long names — likely candidates for shortening). n must be non-negative integer; non-numeric or negative refuses with exit 1. Ops with no object.schema (bare-name + 1-part-FQN refactors) are excluded. OPENS the schema length pair, 2/5 of the LENGTH sub-arc opened iter 325. Composes with --schema-max-length for closed-range queries.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--schema-max-length <n>',\n 'Filter to ops whose target object.schema length is <= n. Useful for naming-convention audits (\"--schema-max-length 3\" finds refactors on suspiciously-short schemas — candidates for expansion). n must be non-negative integer; non-numeric or negative refuses with exit 1. Ops with no object.schema are excluded (a missing schema has no length, can\\'t satisfy a max bound). CLOSES the schema length pair, 2/5 pair of the LENGTH sub-arc. Composes with --schema-min-length for closed-range queries; refuses if min > max when both set (range is empty).',\n (v) => parseInt(v, 10),\n )\n .option(\n '--database-min-length <n>',\n 'Filter to ops whose target object.database length is >= n. Useful for naming-convention audits on the catalog/database axis (\"--database-min-length 20\" finds refactors on databases with suspiciously-long names). n must be non-negative integer; non-numeric or negative refuses with exit 1. Ops with no object.database (2-part and bare-name refactors) are excluded. OPENS the database length pair, 3/5 of the LENGTH sub-arc. Composes with --database-max-length for closed-range queries.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--database-max-length <n>',\n 'Filter to ops whose target object.database length is <= n. Useful for naming-convention audits (\"--database-max-length 3\" finds refactors on suspiciously-short databases — candidates for expansion). n must be non-negative integer; non-numeric or negative refuses with exit 1. Ops with no object.database are excluded (a missing database has no length). CLOSES the database length pair, 3/5 pair of the LENGTH sub-arc. Composes with --database-min-length for closed-range queries; refuses if min > max when both set (range is empty).',\n (v) => parseInt(v, 10),\n )\n .option(\n '--note-min-length <n>',\n 'Filter to ops whose op.note length is >= n. Useful for note-quality audits (\"--note-min-length 40\" finds refactors with substantial annotations — distinguishes thoroughly-documented ones from short stub notes). n must be non-negative integer; non-numeric or negative refuses with exit 1. Ops with no op.note are excluded (a missing note has no length, can\\'t satisfy a min bound); ops with empty-string note are kept when n=0, excluded for n>=1. OPENS the note length pair, 4/5 of the LENGTH sub-arc. Composes with --note-max-length for closed-range queries.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--note-max-length <n>',\n 'Filter to ops whose op.note length is <= n. Useful for note-quality audits (\"--note-max-length 10\" finds refactors with stub notes — candidates for fuller documentation). n must be non-negative integer; non-numeric or negative refuses with exit 1. Ops with no op.note are excluded (a missing note has no length); ops with empty-string note are kept for any non-negative n (length 0 satisfies <=n). CLOSES the note length pair, 4/5 pair of the LENGTH sub-arc. Composes with --note-min-length for closed-range queries; refuses if min > max when both set (range is empty).',\n (v) => parseInt(v, 10),\n )\n .option(\n '--id-min-length <n>',\n 'Filter to ops whose op.id length is >= n. Useful for id-quality audits on the id axis — useful primarily for diagnostic seed-data validation since production UUIDs have a fixed length of 36 (8-4-4-4-12). n must be non-negative integer; non-numeric or negative refuses with exit 1. Ops with no op.id (defensive — every refactor op gets a UUID by contract) are excluded. OPENS the id length pair, 5/5 of the LENGTH sub-arc — completes the axis coverage (name + schema + database + note + id, all 5 axes). Composes with --id-max-length for closed-range queries.',\n (v) => parseInt(v, 10),\n )\n .option(\n '--id-max-length <n>',\n 'Filter to ops whose op.id length is <= n. Useful for id-quality audits (\"--id-max-length 35\" finds refactors with non-UUID short ids — diagnostic seed-data validation). n must be non-negative integer; non-numeric or negative refuses with exit 1. Ops with no op.id are excluded. CLOSES the id length pair AND CLOSES THE ENTIRE LENGTH sub-arc (10 paired flags across 5 axes: name + schema + database + note + id). Composes with --id-min-length for closed-range queries; refuses if min > max when both set (range is empty).',\n (v) => parseInt(v, 10),\n )\n .option(\n '--has-database',\n 'Filter to ops whose target object.database field is set + non-empty. Useful for \"show me only the refactors with a fully-qualified 3-part FQN\" — finds ops where the catalog tier was explicit, distinguishing them from 2-part (schema.name) or bare (name-only) refactors. Composes with --database (intersection, but redundantly — --database already implies a non-empty database). Opens a new HAS/MISSING-IDENT predicate sub-arc on the refactor-list filter surface, mirroring the existing --has-note / --missing-note pair on the NOTE axis (iter 212). First flag of 4-pair sub-arc covering DATABASE + SCHEMA axes (NAME is always present per Op contract; ID is always present per UUID generation contract). Will be mutually exclusive with --missing-database (next iter). (Refactor log records the top container as `database` even though the Databricks term is catalog.)',\n false,\n )\n .option(\n '--missing-database',\n 'Filter to ops whose target object.database field is absent or empty. Complement of --has-database. Useful for \"find the refactors with implicit catalog/database resolution\" — ops where the catalog tier was inferred from the session/connection rather than explicitly named, i.e. 2-part (schema.name) or bare (name-only) FQNs. CLOSES the database HAS/MISSING pair, 1/2 of the HAS/MISSING-IDENT predicate sub-arc opened iter 321. Mutually exclusive with --has-database. (Refactor log records the top container as `database` even though the Databricks term is catalog.)',\n false,\n )\n .option(\n '--has-schema',\n 'Filter to ops whose target object.schema field is set + non-empty. Useful for \"show me only the refactors with an explicit schema qualifier\" — finds ops where the schema tier was named, distinguishing them from bare-name (no schema, no database) refactors. Composes with --schema (intersection, but redundantly — --schema already implies a non-empty schema). Opens the schema HAS/MISSING pair, 2/2 of the HAS/MISSING-IDENT predicate sub-arc opened iter 321. Will be mutually exclusive with --missing-schema (next iter).',\n false,\n )\n .option(\n '--missing-schema',\n 'Filter to ops whose target object.schema field is absent or empty. Complement of --has-schema. Useful for \"find the refactors with implicit schema resolution\" — ops where the schema tier was inferred from the session/connection or omitted entirely (bare-name refactors). CLOSES the schema HAS/MISSING pair AND CLOSES THE ENTIRE HAS/MISSING-IDENT predicate sub-arc (database + schema axes, opened iter 321). Mutually exclusive with --has-schema.',\n false,\n )\n .option(\n '--has-note',\n 'Filter to ops whose note field is set + non-empty. Useful for \"show me only the deliberate refactors that came with documentation.\" Composes with --note-contains (intersection, but redundantly — --note-contains already implies a non-empty note). Mutually exclusive with --missing-note.',\n false,\n )\n .option(\n '--missing-note',\n 'Filter to ops whose note field is absent or empty. Complement of --has-note. Useful for \"find the undocumented refactors that still need annotation.\" Mutually exclusive with --has-note.',\n false,\n )\n .option(\n '--count',\n 'Emit only the integer count of matching ops to stdout (after all filters). Suppresses headline + per-op lines. Composes with --json (emits {count: N}). Useful for shell pipes (`if [ \"$(... --count)\" -gt 0 ]; then ...`). Mutually exclusive with --summary.',\n false,\n )\n .option(\n '--summary',\n 'Emit a summary of matching ops grouped by op.type (one line per non-zero kind, sorted alphabetically) instead of per-op detail. Composes with --json (emits {total: N, byType: {KIND: count}}). Useful for audit overviews. Mutually exclusive with --count.',\n false,\n )\n .option(\n '--csv',\n 'Emit matching ops as CSV (header row + one row per op: id,timestamp,type,database,schema,name,objectType,note). Standard CSV escaping (RFC 4180): fields containing comma/quote/newline are quoted with `\"\"` escape. Useful for spreadsheet ingest. Mutually exclusive with --json, --count, --summary.',\n false,\n )\n .option(\n '--reverse',\n 'Emit operations in reverse chronological order (most-recent first). Applied AFTER --last so \"--last 5 --reverse\" gives the 5 most recent with newest on top.',\n false,\n )\n .option(\n '--bare',\n 'Text output only: omit the \"Refactor log: <path> (...)\" headline and emit just the per-op lines. Useful for piping into `awk` / `wc -l` / other shell tools. No effect on --json output.',\n false,\n )\n .option('--json', 'Emit machine-readable JSON', false)\n .action(\n async (opts: {\n log?: string;\n type?: string;\n notType?: string;\n types?: string;\n notTypes?: string;\n since?: string;\n sinceRelative?: string;\n until?: string;\n untilRelative?: string;\n last?: number;\n first?: number;\n id?: string;\n notId?: string;\n ids?: string;\n notIds?: string;\n idPrefix?: string;\n notIdPrefix?: string;\n idPrefixes?: string;\n notIdPrefixes?: string;\n idSuffix?: string;\n notIdSuffix?: string;\n idSuffixes?: string;\n notIdSuffixes?: string;\n idContains?: string;\n notIdContains?: string;\n idContainsAny?: string;\n notIdContainsAny?: string;\n idContainsAll?: string;\n notIdContainsAll?: string;\n idRegex?: string;\n notIdRegex?: string;\n noteContains?: string;\n notNoteContains?: string;\n noteContainsAny?: string;\n notNoteContainsAny?: string;\n noteContainsAll?: string;\n notNoteContainsAll?: string;\n noteRegex?: string;\n notNoteRegex?: string;\n notePrefix?: string;\n notNotePrefix?: string;\n notePrefixes?: string;\n notNotePrefixes?: string;\n noteSuffix?: string;\n notNoteSuffix?: string;\n noteSuffixes?: string;\n notNoteSuffixes?: string;\n noteExact?: string;\n notNoteExact?: string;\n notes?: string;\n notNotes?: string;\n objectType?: string;\n notObjectType?: string;\n objectTypes?: string;\n notObjectTypes?: string;\n name?: string;\n notName?: string;\n nameContainsAny?: string;\n notNameContainsAny?: string;\n nameContainsAll?: string;\n notNameContainsAll?: string;\n nameRegex?: string;\n notNameRegex?: string;\n namePrefix?: string;\n notNamePrefix?: string;\n namePrefixes?: string;\n notNamePrefixes?: string;\n nameSuffix?: string;\n notNameSuffix?: string;\n nameSuffixes?: string;\n notNameSuffixes?: string;\n nameExact?: string;\n notNameExact?: string;\n names?: string;\n notNames?: string;\n schema?: string;\n notSchema?: string;\n schemaContainsAny?: string;\n notSchemaContainsAny?: string;\n schemaContainsAll?: string;\n notSchemaContainsAll?: string;\n schemaRegex?: string;\n notSchemaRegex?: string;\n schemaPrefix?: string;\n notSchemaPrefix?: string;\n schemaPrefixes?: string;\n notSchemaPrefixes?: string;\n schemaSuffix?: string;\n notSchemaSuffix?: string;\n schemaSuffixes?: string;\n notSchemaSuffixes?: string;\n schemaExact?: string;\n notSchemaExact?: string;\n schemas?: string;\n notSchemas?: string;\n database?: string;\n notDatabase?: string;\n databaseContainsAny?: string;\n notDatabaseContainsAny?: string;\n databaseContainsAll?: string;\n notDatabaseContainsAll?: string;\n databaseRegex?: string;\n notDatabaseRegex?: string;\n databasePrefix?: string;\n notDatabasePrefix?: string;\n databasePrefixes?: string;\n notDatabasePrefixes?: string;\n databaseSuffix?: string;\n notDatabaseSuffix?: string;\n databaseSuffixes?: string;\n notDatabaseSuffixes?: string;\n databaseExact?: string;\n notDatabaseExact?: string;\n databases?: string;\n notDatabases?: string;\n nameMinLength?: number;\n nameMaxLength?: number;\n schemaMinLength?: number;\n schemaMaxLength?: number;\n databaseMinLength?: number;\n databaseMaxLength?: number;\n noteMinLength?: number;\n noteMaxLength?: number;\n idMinLength?: number;\n idMaxLength?: number;\n year?: number;\n years?: string;\n notYear?: number;\n notYears?: string;\n month?: number;\n months?: string;\n notMonth?: number;\n notMonths?: string;\n dayOfWeek?: number;\n daysOfWeek?: string;\n notDayOfWeek?: number;\n notDaysOfWeek?: string;\n hour?: number;\n hours?: string;\n notHour?: number;\n notHours?: string;\n minute?: number;\n minutes?: string;\n notMinute?: number;\n notMinutes?: string;\n second?: number;\n seconds?: string;\n notSecond?: number;\n notSeconds?: string;\n dayOfMonth?: number;\n daysOfMonth?: string;\n notDayOfMonth?: number;\n notDaysOfMonth?: string;\n quarter?: number;\n quarters?: string;\n notQuarter?: number;\n notQuarters?: string;\n dayOfYear?: number;\n daysOfYear?: string;\n notDayOfYear?: number;\n notDaysOfYear?: string;\n weekOfYear?: number;\n weeksOfYear?: string;\n notWeekOfYear?: number;\n notWeeksOfYear?: string;\n weekOfMonth?: number;\n weeksOfMonth?: string;\n notWeekOfMonth?: number;\n notWeeksOfMonth?: string;\n millisecond?: number;\n milliseconds?: string;\n notMillisecond?: number;\n notMilliseconds?: string;\n minuteOfDay?: number;\n minutesOfDay?: string;\n hasDatabase?: boolean;\n missingDatabase?: boolean;\n hasSchema?: boolean;\n missingSchema?: boolean;\n hasNote?: boolean;\n missingNote?: boolean;\n count?: boolean;\n summary?: boolean;\n csv?: boolean;\n reverse?: boolean;\n bare?: boolean;\n json?: boolean;\n }) => {\n const logPath = path.resolve(opts.log ?? DEFAULT_LOG);\n const log = await ensureLogExists(logPath);\n const wantKind = opts.type ? opts.type.toUpperCase() : undefined;\n if (wantKind && !(VALID_OP_KINDS as readonly string[]).includes(wantKind)) {\n console.error(\n `refactor list: --type ${JSON.stringify(opts.type)} not recognized; expected one of ${VALID_OP_KINDS.join(', ')}`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.type !== undefined && opts.notType !== undefined) {\n console.error(`refactor list: --type and --not-type are mutually exclusive; pick one.`);\n process.exitCode = 1;\n return;\n }\n if (opts.types !== undefined && (opts.type !== undefined || opts.notType !== undefined)) {\n console.error(\n `refactor list: --types is mutually exclusive with --type and --not-type; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (\n opts.notTypes !== undefined &&\n (opts.type !== undefined || opts.notType !== undefined || opts.types !== undefined)\n ) {\n console.error(\n `refactor list: --not-types is mutually exclusive with --type, --not-type, and --types; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n const excludeKind = opts.notType ? opts.notType.toUpperCase() : undefined;\n if (excludeKind && !(VALID_OP_KINDS as readonly string[]).includes(excludeKind)) {\n console.error(\n `refactor list: --not-type ${JSON.stringify(opts.notType)} not recognized; expected one of ${VALID_OP_KINDS.join(', ')}`,\n );\n process.exitCode = 1;\n return;\n }\n let wantKindSet: Set<string> | undefined;\n if (opts.types !== undefined) {\n if (typeof opts.types !== 'string' || opts.types.trim().length === 0) {\n console.error(`refactor list: --types must be a non-empty comma-separated list.`);\n process.exitCode = 1;\n return;\n }\n const parsed = opts.types\n .split(',')\n .map((s) => s.trim().toUpperCase())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(`refactor list: --types must contain at least one non-empty value.`);\n process.exitCode = 1;\n return;\n }\n for (const k of parsed) {\n if (!(VALID_OP_KINDS as readonly string[]).includes(k)) {\n console.error(\n `refactor list: --types value ${JSON.stringify(k)} not recognized; expected one of ${VALID_OP_KINDS.join(', ')}`,\n );\n process.exitCode = 1;\n return;\n }\n }\n wantKindSet = new Set(parsed);\n }\n let excludeKindSet: Set<string> | undefined;\n if (opts.notTypes !== undefined) {\n if (typeof opts.notTypes !== 'string' || opts.notTypes.trim().length === 0) {\n console.error(`refactor list: --not-types must be a non-empty comma-separated list.`);\n process.exitCode = 1;\n return;\n }\n const parsed = opts.notTypes\n .split(',')\n .map((s) => s.trim().toUpperCase())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(`refactor list: --not-types must contain at least one non-empty value.`);\n process.exitCode = 1;\n return;\n }\n for (const k of parsed) {\n if (!(VALID_OP_KINDS as readonly string[]).includes(k)) {\n console.error(\n `refactor list: --not-types value ${JSON.stringify(k)} not recognized; expected one of ${VALID_OP_KINDS.join(', ')}`,\n );\n process.exitCode = 1;\n return;\n }\n }\n excludeKindSet = new Set(parsed);\n }\n let sinceMs: number | undefined;\n if (opts.since !== undefined && opts.sinceRelative !== undefined) {\n console.error(\n `refactor list: --since and --since-relative are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.since !== undefined) {\n const parsed = Date.parse(opts.since);\n if (Number.isNaN(parsed)) {\n console.error(\n `refactor list: --since ${JSON.stringify(opts.since)} is not a valid ISO 8601 timestamp.`,\n );\n process.exitCode = 1;\n return;\n }\n sinceMs = parsed;\n }\n if (opts.sinceRelative !== undefined) {\n const m = /^(\\d+)(h|d|w|mo)$/.exec(opts.sinceRelative);\n if (!m) {\n console.error(\n `refactor list: --since-relative ${JSON.stringify(opts.sinceRelative)} is not a valid duration. Expected formats: 7d, 24h, 2w, 3mo.`,\n );\n process.exitCode = 1;\n return;\n }\n const n = parseInt(m[1]!, 10);\n const unit = m[2]!;\n const HOUR = 3600 * 1000;\n const DAY = 24 * HOUR;\n const unitMs: Record<string, number> = {\n h: HOUR,\n d: DAY,\n w: 7 * DAY,\n mo: 30 * DAY, // approximate; documented in flag help\n };\n sinceMs = Date.now() - n * unitMs[unit]!;\n }\n let untilMs: number | undefined;\n if (opts.until !== undefined && opts.untilRelative !== undefined) {\n console.error(\n `refactor list: --until and --until-relative are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.until !== undefined) {\n const parsed = Date.parse(opts.until);\n if (Number.isNaN(parsed)) {\n console.error(\n `refactor list: --until ${JSON.stringify(opts.until)} is not a valid ISO 8601 timestamp.`,\n );\n process.exitCode = 1;\n return;\n }\n untilMs = parsed;\n }\n if (opts.untilRelative !== undefined) {\n const m = /^(\\d+)(h|d|w|mo)$/.exec(opts.untilRelative);\n if (!m) {\n console.error(\n `refactor list: --until-relative ${JSON.stringify(opts.untilRelative)} is not a valid duration. Expected formats: 7d, 24h, 2w, 3mo.`,\n );\n process.exitCode = 1;\n return;\n }\n const n = parseInt(m[1]!, 10);\n const unit = m[2]!;\n const HOUR = 3600 * 1000;\n const DAY = 24 * HOUR;\n const unitMs: Record<string, number> = {\n h: HOUR,\n d: DAY,\n w: 7 * DAY,\n mo: 30 * DAY,\n };\n untilMs = Date.now() - n * unitMs[unit]!;\n }\n if (sinceMs !== undefined && untilMs !== undefined && sinceMs > untilMs) {\n console.error(\n `refactor list: --since ${opts.since} is after --until ${opts.until}; range is empty by definition.`,\n );\n process.exitCode = 1;\n return;\n }\n let operations = wantKind\n ? log.operations.filter((o) => o.type === wantKind)\n : log.operations;\n if (excludeKind) {\n operations = operations.filter((o) => o.type !== excludeKind);\n }\n if (wantKindSet !== undefined) {\n operations = operations.filter((o) => wantKindSet!.has(o.type));\n }\n if (excludeKindSet !== undefined) {\n operations = operations.filter((o) => !excludeKindSet!.has(o.type));\n }\n if (sinceMs !== undefined || untilMs !== undefined) {\n operations = operations.filter((o) => {\n const opMs = Date.parse(o.timestamp);\n // Skip ops with malformed timestamps — never seen in practice but defensive.\n if (Number.isNaN(opMs)) return false;\n if (sinceMs !== undefined && opMs < sinceMs) return false;\n if (untilMs !== undefined && opMs > untilMs) return false;\n return true;\n });\n }\n if (opts.id !== undefined && opts.notId !== undefined) {\n console.error(`refactor list: --id and --not-id are mutually exclusive; pick one.`);\n process.exitCode = 1;\n return;\n }\n if (opts.id !== undefined) {\n if (typeof opts.id !== 'string' || opts.id.trim().length === 0) {\n console.error(`refactor list: --id must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const wantId = opts.id;\n operations = operations.filter((o) => o.id === wantId);\n }\n if (opts.notId !== undefined) {\n if (typeof opts.notId !== 'string' || opts.notId.trim().length === 0) {\n console.error(`refactor list: --not-id must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const notWantId = opts.notId;\n operations = operations.filter((o) => o.id !== notWantId);\n }\n if (opts.ids !== undefined && (opts.id !== undefined || opts.notId !== undefined)) {\n console.error(\n `refactor list: --ids is mutually exclusive with --id and --not-id; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.ids !== undefined) {\n if (typeof opts.ids !== 'string' || opts.ids.trim().length === 0) {\n console.error(`refactor list: --ids must be a non-empty comma-separated list.`);\n process.exitCode = 1;\n return;\n }\n const parsed = opts.ids\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(`refactor list: --ids must contain at least one non-empty value.`);\n process.exitCode = 1;\n return;\n }\n const wantSet = new Set(parsed);\n operations = operations.filter((o) => wantSet.has(o.id));\n }\n if (\n opts.notIds !== undefined &&\n (opts.id !== undefined || opts.notId !== undefined || opts.ids !== undefined)\n ) {\n console.error(\n `refactor list: --not-ids is mutually exclusive with --id, --not-id, and --ids; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notIds !== undefined) {\n if (typeof opts.notIds !== 'string' || opts.notIds.trim().length === 0) {\n console.error(`refactor list: --not-ids must be a non-empty comma-separated list.`);\n process.exitCode = 1;\n return;\n }\n const parsed = opts.notIds\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(`refactor list: --not-ids must contain at least one non-empty value.`);\n process.exitCode = 1;\n return;\n }\n const excludeSet = new Set(parsed);\n operations = operations.filter((o) => !excludeSet.has(o.id));\n }\n if (opts.idPrefix !== undefined && opts.notIdPrefix !== undefined) {\n console.error(\n `refactor list: --id-prefix and --not-id-prefix are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.idPrefix !== undefined) {\n if (typeof opts.idPrefix !== 'string' || opts.idPrefix.length === 0) {\n console.error(`refactor list: --id-prefix must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const prefix = opts.idPrefix;\n operations = operations.filter(\n (o) => typeof o.id === 'string' && o.id.startsWith(prefix),\n );\n }\n if (opts.notIdPrefix !== undefined) {\n if (typeof opts.notIdPrefix !== 'string' || opts.notIdPrefix.length === 0) {\n console.error(`refactor list: --not-id-prefix must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const notPrefix = opts.notIdPrefix;\n operations = operations.filter(\n (o) => typeof o.id === 'string' && !o.id.startsWith(notPrefix),\n );\n }\n if (\n opts.idPrefixes !== undefined &&\n (opts.idPrefix !== undefined || opts.notIdPrefix !== undefined)\n ) {\n console.error(\n `refactor list: --id-prefixes is mutually exclusive with --id-prefix and --not-id-prefix; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.idPrefixes !== undefined) {\n if (typeof opts.idPrefixes !== 'string' || opts.idPrefixes.trim().length === 0) {\n console.error(`refactor list: --id-prefixes must be a non-empty comma-separated list.`);\n process.exitCode = 1;\n return;\n }\n const parsed = opts.idPrefixes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --id-prefixes must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.id !== 'string') return false;\n return parsed.some((p) => o.id.startsWith(p));\n });\n }\n if (\n opts.notIdPrefixes !== undefined &&\n (opts.idPrefix !== undefined ||\n opts.notIdPrefix !== undefined ||\n opts.idPrefixes !== undefined)\n ) {\n console.error(\n `refactor list: --not-id-prefixes is mutually exclusive with --id-prefix, --not-id-prefix, and --id-prefixes; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notIdPrefixes !== undefined) {\n if (typeof opts.notIdPrefixes !== 'string' || opts.notIdPrefixes.trim().length === 0) {\n console.error(\n `refactor list: --not-id-prefixes must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.notIdPrefixes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --not-id-prefixes must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.id !== 'string') return false;\n return !parsed.some((p) => o.id.startsWith(p));\n });\n }\n if (opts.idSuffix !== undefined && opts.notIdSuffix !== undefined) {\n console.error(\n `refactor list: --id-suffix and --not-id-suffix are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.idSuffix !== undefined) {\n if (typeof opts.idSuffix !== 'string' || opts.idSuffix.length === 0) {\n console.error(`refactor list: --id-suffix must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const suffix = opts.idSuffix;\n operations = operations.filter((o) => typeof o.id === 'string' && o.id.endsWith(suffix));\n }\n if (opts.notIdSuffix !== undefined) {\n if (typeof opts.notIdSuffix !== 'string' || opts.notIdSuffix.length === 0) {\n console.error(`refactor list: --not-id-suffix must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const notSuffix = opts.notIdSuffix;\n operations = operations.filter(\n (o) => typeof o.id === 'string' && !o.id.endsWith(notSuffix),\n );\n }\n if (\n opts.idSuffixes !== undefined &&\n (opts.idSuffix !== undefined || opts.notIdSuffix !== undefined)\n ) {\n console.error(\n `refactor list: --id-suffixes is mutually exclusive with --id-suffix and --not-id-suffix; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.idSuffixes !== undefined) {\n if (typeof opts.idSuffixes !== 'string' || opts.idSuffixes.trim().length === 0) {\n console.error(`refactor list: --id-suffixes must be a non-empty comma-separated list.`);\n process.exitCode = 1;\n return;\n }\n const parsed = opts.idSuffixes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --id-suffixes must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.id !== 'string') return false;\n return parsed.some((s) => o.id.endsWith(s));\n });\n }\n if (\n opts.notIdSuffixes !== undefined &&\n (opts.idSuffix !== undefined ||\n opts.notIdSuffix !== undefined ||\n opts.idSuffixes !== undefined)\n ) {\n console.error(\n `refactor list: --not-id-suffixes is mutually exclusive with --id-suffix, --not-id-suffix, and --id-suffixes; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notIdSuffixes !== undefined) {\n if (typeof opts.notIdSuffixes !== 'string' || opts.notIdSuffixes.trim().length === 0) {\n console.error(\n `refactor list: --not-id-suffixes must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.notIdSuffixes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --not-id-suffixes must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.id !== 'string') return false;\n return !parsed.some((s) => o.id.endsWith(s));\n });\n }\n if (opts.idContains !== undefined && opts.notIdContains !== undefined) {\n console.error(\n `refactor list: --id-contains and --not-id-contains are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.idContains !== undefined) {\n if (typeof opts.idContains !== 'string' || opts.idContains.length === 0) {\n console.error(`refactor list: --id-contains must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const needle = opts.idContains;\n operations = operations.filter((o) => typeof o.id === 'string' && o.id.includes(needle));\n }\n if (opts.notIdContains !== undefined) {\n if (typeof opts.notIdContains !== 'string' || opts.notIdContains.length === 0) {\n console.error(`refactor list: --not-id-contains must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const notNeedle = opts.notIdContains;\n operations = operations.filter(\n (o) => typeof o.id === 'string' && !o.id.includes(notNeedle),\n );\n }\n if (\n opts.idContainsAny !== undefined &&\n (opts.idContains !== undefined || opts.notIdContains !== undefined)\n ) {\n console.error(\n `refactor list: --id-contains-any is mutually exclusive with --id-contains and --not-id-contains; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.idContainsAny !== undefined) {\n if (typeof opts.idContainsAny !== 'string' || opts.idContainsAny.trim().length === 0) {\n console.error(\n `refactor list: --id-contains-any must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.idContainsAny\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --id-contains-any must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.id !== 'string') return false;\n const idStr = o.id;\n return parsed.some((s) => idStr.includes(s));\n });\n }\n if (\n opts.notIdContainsAny !== undefined &&\n (opts.idContains !== undefined ||\n opts.notIdContains !== undefined ||\n opts.idContainsAny !== undefined)\n ) {\n console.error(\n `refactor list: --not-id-contains-any is mutually exclusive with --id-contains, --not-id-contains, and --id-contains-any; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notIdContainsAny !== undefined) {\n if (\n typeof opts.notIdContainsAny !== 'string' ||\n opts.notIdContainsAny.trim().length === 0\n ) {\n console.error(\n `refactor list: --not-id-contains-any must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.notIdContainsAny\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --not-id-contains-any must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.id !== 'string') return true;\n const idStr = o.id;\n return !parsed.some((s) => idStr.includes(s));\n });\n }\n if (\n opts.idContainsAll !== undefined &&\n (opts.idContains !== undefined ||\n opts.notIdContains !== undefined ||\n opts.idContainsAny !== undefined ||\n opts.notIdContainsAny !== undefined)\n ) {\n console.error(\n `refactor list: --id-contains-all is mutually exclusive with --id-contains, --not-id-contains, --id-contains-any, and --not-id-contains-any; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.idContainsAll !== undefined) {\n if (typeof opts.idContainsAll !== 'string' || opts.idContainsAll.trim().length === 0) {\n console.error(\n `refactor list: --id-contains-all must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.idContainsAll\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --id-contains-all must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.id !== 'string') return false;\n const idStr = o.id;\n return parsed.every((s) => idStr.includes(s));\n });\n }\n if (\n opts.notIdContainsAll !== undefined &&\n (opts.idContains !== undefined ||\n opts.notIdContains !== undefined ||\n opts.idContainsAny !== undefined ||\n opts.notIdContainsAny !== undefined ||\n opts.idContainsAll !== undefined)\n ) {\n console.error(\n `refactor list: --not-id-contains-all is mutually exclusive with --id-contains, --not-id-contains, --id-contains-any, --not-id-contains-any, and --id-contains-all; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notIdContainsAll !== undefined) {\n if (\n typeof opts.notIdContainsAll !== 'string' ||\n opts.notIdContainsAll.trim().length === 0\n ) {\n console.error(\n `refactor list: --not-id-contains-all must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.notIdContainsAll\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --not-id-contains-all must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.id !== 'string') return true;\n const idStr = o.id;\n return !parsed.every((s) => idStr.includes(s));\n });\n }\n if (\n opts.idRegex !== undefined &&\n (opts.idContains !== undefined ||\n opts.notIdContains !== undefined ||\n opts.idContainsAny !== undefined ||\n opts.notIdContainsAny !== undefined ||\n opts.idContainsAll !== undefined ||\n opts.notIdContainsAll !== undefined)\n ) {\n console.error(\n `refactor list: --id-regex is mutually exclusive with --id-contains, --not-id-contains, --id-contains-any, --not-id-contains-any, --id-contains-all, and --not-id-contains-all; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.idRegex !== undefined) {\n if (typeof opts.idRegex !== 'string' || opts.idRegex.length === 0) {\n console.error(`refactor list: --id-regex must be a non-empty pattern.`);\n process.exitCode = 1;\n return;\n }\n let idPattern: RegExp;\n try {\n idPattern = new RegExp(opts.idRegex);\n } catch (err) {\n console.error(\n `refactor list: --id-regex invalid regex pattern: ${(err as Error).message}`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.id !== 'string') return false;\n return idPattern.test(o.id);\n });\n }\n if (\n opts.notIdRegex !== undefined &&\n (opts.idContains !== undefined ||\n opts.notIdContains !== undefined ||\n opts.idContainsAny !== undefined ||\n opts.notIdContainsAny !== undefined ||\n opts.idContainsAll !== undefined ||\n opts.notIdContainsAll !== undefined ||\n opts.idRegex !== undefined)\n ) {\n console.error(\n `refactor list: --not-id-regex is mutually exclusive with --id-contains, --not-id-contains, --id-contains-any, --not-id-contains-any, --id-contains-all, --not-id-contains-all, and --id-regex; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notIdRegex !== undefined) {\n if (typeof opts.notIdRegex !== 'string' || opts.notIdRegex.length === 0) {\n console.error(`refactor list: --not-id-regex must be a non-empty pattern.`);\n process.exitCode = 1;\n return;\n }\n let notIdPattern: RegExp;\n try {\n notIdPattern = new RegExp(opts.notIdRegex);\n } catch (err) {\n console.error(\n `refactor list: --not-id-regex invalid regex pattern: ${(err as Error).message}`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.id !== 'string') return true;\n return !notIdPattern.test(o.id);\n });\n }\n if (opts.noteContains !== undefined && opts.notNoteContains !== undefined) {\n console.error(\n `refactor list: --note-contains and --not-note-contains are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.noteContains !== undefined) {\n if (typeof opts.noteContains !== 'string' || opts.noteContains.length === 0) {\n console.error(`refactor list: --note-contains must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const needleLower = opts.noteContains.toLowerCase();\n operations = operations.filter(\n (o) => typeof o.note === 'string' && o.note.toLowerCase().includes(needleLower),\n );\n }\n if (opts.notNoteContains !== undefined) {\n if (typeof opts.notNoteContains !== 'string' || opts.notNoteContains.length === 0) {\n console.error(`refactor list: --not-note-contains must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const notNeedleLower = opts.notNoteContains.toLowerCase();\n operations = operations.filter(\n (o) => typeof o.note !== 'string' || !o.note.toLowerCase().includes(notNeedleLower),\n );\n }\n if (\n opts.noteContainsAny !== undefined &&\n (opts.noteContains !== undefined || opts.notNoteContains !== undefined)\n ) {\n console.error(\n `refactor list: --note-contains-any is mutually exclusive with --note-contains and --not-note-contains; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.noteContainsAny !== undefined) {\n if (\n typeof opts.noteContainsAny !== 'string' ||\n opts.noteContainsAny.trim().length === 0\n ) {\n console.error(\n `refactor list: --note-contains-any must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.noteContainsAny\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --note-contains-any must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsedLower = parsed.map((s) => s.toLowerCase());\n operations = operations.filter((o) => {\n if (typeof o.note !== 'string') return false;\n const noteLower = o.note.toLowerCase();\n return parsedLower.some((s) => noteLower.includes(s));\n });\n }\n if (\n opts.notNoteContainsAny !== undefined &&\n (opts.noteContains !== undefined ||\n opts.notNoteContains !== undefined ||\n opts.noteContainsAny !== undefined)\n ) {\n console.error(\n `refactor list: --not-note-contains-any is mutually exclusive with --note-contains, --not-note-contains, and --note-contains-any; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notNoteContainsAny !== undefined) {\n if (\n typeof opts.notNoteContainsAny !== 'string' ||\n opts.notNoteContainsAny.trim().length === 0\n ) {\n console.error(\n `refactor list: --not-note-contains-any must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.notNoteContainsAny\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --not-note-contains-any must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsedLower = parsed.map((s) => s.toLowerCase());\n operations = operations.filter((o) => {\n if (typeof o.note !== 'string') return true;\n const noteLower = o.note.toLowerCase();\n return !parsedLower.some((s) => noteLower.includes(s));\n });\n }\n if (\n opts.noteContainsAll !== undefined &&\n (opts.noteContains !== undefined ||\n opts.notNoteContains !== undefined ||\n opts.noteContainsAny !== undefined ||\n opts.notNoteContainsAny !== undefined)\n ) {\n console.error(\n `refactor list: --note-contains-all is mutually exclusive with --note-contains, --not-note-contains, --note-contains-any, and --not-note-contains-any; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.noteContainsAll !== undefined) {\n if (\n typeof opts.noteContainsAll !== 'string' ||\n opts.noteContainsAll.trim().length === 0\n ) {\n console.error(\n `refactor list: --note-contains-all must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.noteContainsAll\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --note-contains-all must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsedLower = parsed.map((s) => s.toLowerCase());\n operations = operations.filter((o) => {\n if (typeof o.note !== 'string') return false;\n const noteLower = o.note.toLowerCase();\n return parsedLower.every((s) => noteLower.includes(s));\n });\n }\n if (\n opts.notNoteContainsAll !== undefined &&\n (opts.noteContains !== undefined ||\n opts.notNoteContains !== undefined ||\n opts.noteContainsAny !== undefined ||\n opts.notNoteContainsAny !== undefined ||\n opts.noteContainsAll !== undefined)\n ) {\n console.error(\n `refactor list: --not-note-contains-all is mutually exclusive with --note-contains, --not-note-contains, --note-contains-any, --not-note-contains-any, and --note-contains-all; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notNoteContainsAll !== undefined) {\n if (\n typeof opts.notNoteContainsAll !== 'string' ||\n opts.notNoteContainsAll.trim().length === 0\n ) {\n console.error(\n `refactor list: --not-note-contains-all must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.notNoteContainsAll\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --not-note-contains-all must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsedLower = parsed.map((s) => s.toLowerCase());\n operations = operations.filter((o) => {\n if (typeof o.note !== 'string') return true;\n const noteLower = o.note.toLowerCase();\n return !parsedLower.every((s) => noteLower.includes(s));\n });\n }\n if (\n opts.noteRegex !== undefined &&\n (opts.noteContains !== undefined ||\n opts.notNoteContains !== undefined ||\n opts.noteContainsAny !== undefined ||\n opts.notNoteContainsAny !== undefined ||\n opts.noteContainsAll !== undefined ||\n opts.notNoteContainsAll !== undefined)\n ) {\n console.error(\n `refactor list: --note-regex is mutually exclusive with --note-contains, --not-note-contains, --note-contains-any, --not-note-contains-any, --note-contains-all, and --not-note-contains-all; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.noteRegex !== undefined) {\n if (typeof opts.noteRegex !== 'string' || opts.noteRegex.length === 0) {\n console.error(`refactor list: --note-regex must be a non-empty pattern.`);\n process.exitCode = 1;\n return;\n }\n let notePattern: RegExp;\n try {\n notePattern = new RegExp(opts.noteRegex, 'i');\n } catch (err) {\n console.error(\n `refactor list: --note-regex invalid regex pattern: ${(err as Error).message}`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.note !== 'string') return false;\n return notePattern.test(o.note);\n });\n }\n if (\n opts.notNoteRegex !== undefined &&\n (opts.noteContains !== undefined ||\n opts.notNoteContains !== undefined ||\n opts.noteContainsAny !== undefined ||\n opts.notNoteContainsAny !== undefined ||\n opts.noteContainsAll !== undefined ||\n opts.notNoteContainsAll !== undefined ||\n opts.noteRegex !== undefined)\n ) {\n console.error(\n `refactor list: --not-note-regex is mutually exclusive with --note-contains, --not-note-contains, --note-contains-any, --not-note-contains-any, --note-contains-all, --not-note-contains-all, and --note-regex; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notNoteRegex !== undefined) {\n if (typeof opts.notNoteRegex !== 'string' || opts.notNoteRegex.length === 0) {\n console.error(`refactor list: --not-note-regex must be a non-empty pattern.`);\n process.exitCode = 1;\n return;\n }\n let notNotePattern: RegExp;\n try {\n notNotePattern = new RegExp(opts.notNoteRegex, 'i');\n } catch (err) {\n console.error(\n `refactor list: --not-note-regex invalid regex pattern: ${(err as Error).message}`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.note !== 'string') return true;\n return !notNotePattern.test(o.note);\n });\n }\n if (opts.notePrefix !== undefined && opts.notNotePrefix !== undefined) {\n console.error(\n `refactor list: --note-prefix and --not-note-prefix are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notePrefix !== undefined) {\n if (typeof opts.notePrefix !== 'string' || opts.notePrefix.length === 0) {\n console.error(`refactor list: --note-prefix must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const prefixLower = opts.notePrefix.toLowerCase();\n operations = operations.filter(\n (o) => typeof o.note === 'string' && o.note.toLowerCase().startsWith(prefixLower),\n );\n }\n if (opts.notNotePrefix !== undefined) {\n if (typeof opts.notNotePrefix !== 'string' || opts.notNotePrefix.length === 0) {\n console.error(`refactor list: --not-note-prefix must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const notPrefixLower = opts.notNotePrefix.toLowerCase();\n operations = operations.filter(\n (o) => typeof o.note !== 'string' || !o.note.toLowerCase().startsWith(notPrefixLower),\n );\n }\n if (\n opts.notePrefixes !== undefined &&\n (opts.notePrefix !== undefined || opts.notNotePrefix !== undefined)\n ) {\n console.error(\n `refactor list: --note-prefixes is mutually exclusive with --note-prefix and --not-note-prefix; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notePrefixes !== undefined) {\n if (typeof opts.notePrefixes !== 'string' || opts.notePrefixes.trim().length === 0) {\n console.error(\n `refactor list: --note-prefixes must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.notePrefixes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --note-prefixes must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsedLower = parsed.map((p) => p.toLowerCase());\n operations = operations.filter((o) => {\n if (typeof o.note !== 'string') return false;\n const noteLower = o.note.toLowerCase();\n return parsedLower.some((p) => noteLower.startsWith(p));\n });\n }\n if (\n opts.notNotePrefixes !== undefined &&\n (opts.notePrefix !== undefined ||\n opts.notNotePrefix !== undefined ||\n opts.notePrefixes !== undefined)\n ) {\n console.error(\n `refactor list: --not-note-prefixes is mutually exclusive with --note-prefix, --not-note-prefix, and --note-prefixes; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notNotePrefixes !== undefined) {\n if (\n typeof opts.notNotePrefixes !== 'string' ||\n opts.notNotePrefixes.trim().length === 0\n ) {\n console.error(\n `refactor list: --not-note-prefixes must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.notNotePrefixes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --not-note-prefixes must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsedLower = parsed.map((p) => p.toLowerCase());\n operations = operations.filter((o) => {\n if (typeof o.note !== 'string') return true;\n const noteLower = o.note.toLowerCase();\n return !parsedLower.some((p) => noteLower.startsWith(p));\n });\n }\n if (opts.noteSuffix !== undefined && opts.notNoteSuffix !== undefined) {\n console.error(\n `refactor list: --note-suffix and --not-note-suffix are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.noteSuffix !== undefined) {\n if (typeof opts.noteSuffix !== 'string' || opts.noteSuffix.length === 0) {\n console.error(`refactor list: --note-suffix must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const suffixLower = opts.noteSuffix.toLowerCase();\n operations = operations.filter(\n (o) => typeof o.note === 'string' && o.note.toLowerCase().endsWith(suffixLower),\n );\n }\n if (opts.notNoteSuffix !== undefined) {\n if (typeof opts.notNoteSuffix !== 'string' || opts.notNoteSuffix.length === 0) {\n console.error(`refactor list: --not-note-suffix must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const notSuffixLower = opts.notNoteSuffix.toLowerCase();\n operations = operations.filter(\n (o) => typeof o.note !== 'string' || !o.note.toLowerCase().endsWith(notSuffixLower),\n );\n }\n if (\n opts.noteSuffixes !== undefined &&\n (opts.noteSuffix !== undefined || opts.notNoteSuffix !== undefined)\n ) {\n console.error(\n `refactor list: --note-suffixes is mutually exclusive with --note-suffix and --not-note-suffix; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.noteSuffixes !== undefined) {\n if (typeof opts.noteSuffixes !== 'string' || opts.noteSuffixes.trim().length === 0) {\n console.error(\n `refactor list: --note-suffixes must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.noteSuffixes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --note-suffixes must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsedLower = parsed.map((s) => s.toLowerCase());\n operations = operations.filter((o) => {\n if (typeof o.note !== 'string') return false;\n const noteLower = o.note.toLowerCase();\n return parsedLower.some((s) => noteLower.endsWith(s));\n });\n }\n if (\n opts.notNoteSuffixes !== undefined &&\n (opts.noteSuffix !== undefined ||\n opts.notNoteSuffix !== undefined ||\n opts.noteSuffixes !== undefined)\n ) {\n console.error(\n `refactor list: --not-note-suffixes is mutually exclusive with --note-suffix, --not-note-suffix, and --note-suffixes; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notNoteSuffixes !== undefined) {\n if (\n typeof opts.notNoteSuffixes !== 'string' ||\n opts.notNoteSuffixes.trim().length === 0\n ) {\n console.error(\n `refactor list: --not-note-suffixes must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.notNoteSuffixes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --not-note-suffixes must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsedLower = parsed.map((s) => s.toLowerCase());\n operations = operations.filter((o) => {\n if (typeof o.note !== 'string') return true;\n const noteLower = o.note.toLowerCase();\n return !parsedLower.some((s) => noteLower.endsWith(s));\n });\n }\n if (opts.noteExact !== undefined && opts.notNoteExact !== undefined) {\n console.error(\n `refactor list: --note-exact and --not-note-exact are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.noteExact !== undefined) {\n if (typeof opts.noteExact !== 'string' || opts.noteExact.length === 0) {\n console.error(`refactor list: --note-exact must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const noteExactLower = opts.noteExact.toLowerCase();\n operations = operations.filter(\n (o) => typeof o.note === 'string' && o.note.toLowerCase() === noteExactLower,\n );\n }\n if (opts.notNoteExact !== undefined) {\n if (typeof opts.notNoteExact !== 'string' || opts.notNoteExact.length === 0) {\n console.error(`refactor list: --not-note-exact must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const notNoteExactLower = opts.notNoteExact.toLowerCase();\n operations = operations.filter(\n (o) => typeof o.note !== 'string' || o.note.toLowerCase() !== notNoteExactLower,\n );\n }\n if (\n opts.notes !== undefined &&\n (opts.noteExact !== undefined || opts.notNoteExact !== undefined)\n ) {\n console.error(\n `refactor list: --notes is mutually exclusive with --note-exact and --not-note-exact; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notes !== undefined) {\n if (typeof opts.notes !== 'string' || opts.notes.trim().length === 0) {\n console.error(`refactor list: --notes must be a non-empty comma-separated list.`);\n process.exitCode = 1;\n return;\n }\n const parsed = opts.notes\n .split(',')\n .map((s) => s.trim().toLowerCase())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(`refactor list: --notes must contain at least one non-empty value.`);\n process.exitCode = 1;\n return;\n }\n const wantSet = new Set(parsed);\n operations = operations.filter(\n (o) => typeof o.note === 'string' && wantSet.has(o.note.toLowerCase()),\n );\n }\n if (\n opts.notNotes !== undefined &&\n (opts.noteExact !== undefined ||\n opts.notNoteExact !== undefined ||\n opts.notes !== undefined)\n ) {\n console.error(\n `refactor list: --not-notes is mutually exclusive with --note-exact, --not-note-exact, and --notes; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notNotes !== undefined) {\n if (typeof opts.notNotes !== 'string' || opts.notNotes.trim().length === 0) {\n console.error(`refactor list: --not-notes must be a non-empty comma-separated list.`);\n process.exitCode = 1;\n return;\n }\n const parsed = opts.notNotes\n .split(',')\n .map((s) => s.trim().toLowerCase())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(`refactor list: --not-notes must contain at least one non-empty value.`);\n process.exitCode = 1;\n return;\n }\n const excludeSet = new Set(parsed);\n operations = operations.filter(\n (o) => typeof o.note !== 'string' || !excludeSet.has(o.note.toLowerCase()),\n );\n }\n if (opts.objectType !== undefined && opts.notObjectType !== undefined) {\n console.error(\n `refactor list: --object-type and --not-object-type are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.objectType !== undefined) {\n if (typeof opts.objectType !== 'string' || opts.objectType.trim().length === 0) {\n console.error(`refactor list: --object-type must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const wantObjectType = opts.objectType.toUpperCase();\n operations = operations.filter(\n (o) =>\n typeof o.object?.objectType === 'string' &&\n o.object.objectType.toUpperCase() === wantObjectType,\n );\n }\n if (opts.notObjectType !== undefined) {\n if (typeof opts.notObjectType !== 'string' || opts.notObjectType.trim().length === 0) {\n console.error(`refactor list: --not-object-type must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const excludeObjectType = opts.notObjectType.toUpperCase();\n operations = operations.filter(\n (o) =>\n typeof o.object?.objectType === 'string' &&\n o.object.objectType.toUpperCase() !== excludeObjectType,\n );\n }\n if (\n opts.objectTypes !== undefined &&\n (opts.objectType !== undefined || opts.notObjectType !== undefined)\n ) {\n console.error(\n `refactor list: --object-types is mutually exclusive with --object-type and --not-object-type; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (\n opts.notObjectTypes !== undefined &&\n (opts.objectType !== undefined ||\n opts.notObjectType !== undefined ||\n opts.objectTypes !== undefined)\n ) {\n console.error(\n `refactor list: --not-object-types is mutually exclusive with --object-type, --not-object-type, and --object-types; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.objectTypes !== undefined) {\n if (typeof opts.objectTypes !== 'string' || opts.objectTypes.trim().length === 0) {\n console.error(\n `refactor list: --object-types must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.objectTypes\n .split(',')\n .map((s) => s.trim().toUpperCase())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --object-types must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n const wantSet = new Set(parsed);\n operations = operations.filter(\n (o) =>\n typeof o.object?.objectType === 'string' &&\n wantSet.has(o.object.objectType.toUpperCase()),\n );\n }\n if (opts.notObjectTypes !== undefined) {\n if (typeof opts.notObjectTypes !== 'string' || opts.notObjectTypes.trim().length === 0) {\n console.error(\n `refactor list: --not-object-types must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.notObjectTypes\n .split(',')\n .map((s) => s.trim().toUpperCase())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --not-object-types must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n const excludeSet = new Set(parsed);\n operations = operations.filter(\n (o) =>\n typeof o.object?.objectType === 'string' &&\n !excludeSet.has(o.object.objectType.toUpperCase()),\n );\n }\n if (opts.name !== undefined && opts.notName !== undefined) {\n console.error(`refactor list: --name and --not-name are mutually exclusive; pick one.`);\n process.exitCode = 1;\n return;\n }\n if (opts.name !== undefined) {\n if (typeof opts.name !== 'string' || opts.name.length === 0) {\n console.error(`refactor list: --name must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const nameNeedleLower = opts.name.toLowerCase();\n operations = operations.filter(\n (o) =>\n typeof o.object?.name === 'string' &&\n o.object.name.toLowerCase().includes(nameNeedleLower),\n );\n }\n if (opts.notName !== undefined) {\n if (typeof opts.notName !== 'string' || opts.notName.length === 0) {\n console.error(`refactor list: --not-name must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const notNameNeedleLower = opts.notName.toLowerCase();\n operations = operations.filter(\n (o) =>\n typeof o.object?.name === 'string' &&\n !o.object.name.toLowerCase().includes(notNameNeedleLower),\n );\n }\n if (\n opts.nameContainsAny !== undefined &&\n (opts.name !== undefined || opts.notName !== undefined)\n ) {\n console.error(\n `refactor list: --name-contains-any is mutually exclusive with --name and --not-name; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.nameContainsAny !== undefined) {\n if (\n typeof opts.nameContainsAny !== 'string' ||\n opts.nameContainsAny.trim().length === 0\n ) {\n console.error(\n `refactor list: --name-contains-any must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.nameContainsAny\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --name-contains-any must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsedLower = parsed.map((s) => s.toLowerCase());\n operations = operations.filter((o) => {\n if (typeof o.object?.name !== 'string') return false;\n const nameLower = o.object.name.toLowerCase();\n return parsedLower.some((s) => nameLower.includes(s));\n });\n }\n if (\n opts.notNameContainsAny !== undefined &&\n (opts.name !== undefined ||\n opts.notName !== undefined ||\n opts.nameContainsAny !== undefined)\n ) {\n console.error(\n `refactor list: --not-name-contains-any is mutually exclusive with --name, --not-name, and --name-contains-any; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notNameContainsAny !== undefined) {\n if (\n typeof opts.notNameContainsAny !== 'string' ||\n opts.notNameContainsAny.trim().length === 0\n ) {\n console.error(\n `refactor list: --not-name-contains-any must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.notNameContainsAny\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --not-name-contains-any must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsedLower = parsed.map((s) => s.toLowerCase());\n operations = operations.filter((o) => {\n if (typeof o.object?.name !== 'string') return true;\n const nameLower = o.object.name.toLowerCase();\n return !parsedLower.some((s) => nameLower.includes(s));\n });\n }\n if (\n opts.nameContainsAll !== undefined &&\n (opts.name !== undefined ||\n opts.notName !== undefined ||\n opts.nameContainsAny !== undefined ||\n opts.notNameContainsAny !== undefined)\n ) {\n console.error(\n `refactor list: --name-contains-all is mutually exclusive with --name, --not-name, --name-contains-any, and --not-name-contains-any; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.nameContainsAll !== undefined) {\n if (\n typeof opts.nameContainsAll !== 'string' ||\n opts.nameContainsAll.trim().length === 0\n ) {\n console.error(\n `refactor list: --name-contains-all must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.nameContainsAll\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --name-contains-all must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsedLower = parsed.map((s) => s.toLowerCase());\n operations = operations.filter((o) => {\n if (typeof o.object?.name !== 'string') return false;\n const nameLower = o.object.name.toLowerCase();\n return parsedLower.every((s) => nameLower.includes(s));\n });\n }\n if (\n opts.notNameContainsAll !== undefined &&\n (opts.name !== undefined ||\n opts.notName !== undefined ||\n opts.nameContainsAny !== undefined ||\n opts.notNameContainsAny !== undefined ||\n opts.nameContainsAll !== undefined)\n ) {\n console.error(\n `refactor list: --not-name-contains-all is mutually exclusive with --name, --not-name, --name-contains-any, --not-name-contains-any, and --name-contains-all; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notNameContainsAll !== undefined) {\n if (\n typeof opts.notNameContainsAll !== 'string' ||\n opts.notNameContainsAll.trim().length === 0\n ) {\n console.error(\n `refactor list: --not-name-contains-all must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.notNameContainsAll\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --not-name-contains-all must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsedLower = parsed.map((s) => s.toLowerCase());\n operations = operations.filter((o) => {\n if (typeof o.object?.name !== 'string') return true;\n const nameLower = o.object.name.toLowerCase();\n return !parsedLower.every((s) => nameLower.includes(s));\n });\n }\n if (\n opts.nameRegex !== undefined &&\n (opts.name !== undefined ||\n opts.notName !== undefined ||\n opts.nameContainsAny !== undefined ||\n opts.notNameContainsAny !== undefined ||\n opts.nameContainsAll !== undefined ||\n opts.notNameContainsAll !== undefined)\n ) {\n console.error(\n `refactor list: --name-regex is mutually exclusive with --name, --not-name, --name-contains-any, --not-name-contains-any, --name-contains-all, and --not-name-contains-all; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.nameRegex !== undefined) {\n if (typeof opts.nameRegex !== 'string' || opts.nameRegex.length === 0) {\n console.error(`refactor list: --name-regex must be a non-empty pattern.`);\n process.exitCode = 1;\n return;\n }\n let namePattern: RegExp;\n try {\n namePattern = new RegExp(opts.nameRegex, 'i');\n } catch (err) {\n console.error(\n `refactor list: --name-regex invalid regex pattern: ${(err as Error).message}`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.object?.name !== 'string') return false;\n return namePattern.test(o.object.name);\n });\n }\n if (\n opts.notNameRegex !== undefined &&\n (opts.name !== undefined ||\n opts.notName !== undefined ||\n opts.nameContainsAny !== undefined ||\n opts.notNameContainsAny !== undefined ||\n opts.nameContainsAll !== undefined ||\n opts.notNameContainsAll !== undefined ||\n opts.nameRegex !== undefined)\n ) {\n console.error(\n `refactor list: --not-name-regex is mutually exclusive with --name, --not-name, --name-contains-any, --not-name-contains-any, --name-contains-all, --not-name-contains-all, and --name-regex; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notNameRegex !== undefined) {\n if (typeof opts.notNameRegex !== 'string' || opts.notNameRegex.length === 0) {\n console.error(`refactor list: --not-name-regex must be a non-empty pattern.`);\n process.exitCode = 1;\n return;\n }\n let notNamePattern: RegExp;\n try {\n notNamePattern = new RegExp(opts.notNameRegex, 'i');\n } catch (err) {\n console.error(\n `refactor list: --not-name-regex invalid regex pattern: ${(err as Error).message}`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.object?.name !== 'string') return true;\n return !notNamePattern.test(o.object.name);\n });\n }\n if (opts.namePrefix !== undefined && opts.notNamePrefix !== undefined) {\n console.error(\n `refactor list: --name-prefix and --not-name-prefix are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.namePrefix !== undefined) {\n if (typeof opts.namePrefix !== 'string' || opts.namePrefix.length === 0) {\n console.error(`refactor list: --name-prefix must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const namePrefixLower = opts.namePrefix.toLowerCase();\n operations = operations.filter(\n (o) =>\n typeof o.object?.name === 'string' &&\n o.object.name.toLowerCase().startsWith(namePrefixLower),\n );\n }\n if (opts.notNamePrefix !== undefined) {\n if (typeof opts.notNamePrefix !== 'string' || opts.notNamePrefix.length === 0) {\n console.error(`refactor list: --not-name-prefix must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const notNamePrefixLower = opts.notNamePrefix.toLowerCase();\n operations = operations.filter(\n (o) =>\n typeof o.object?.name === 'string' &&\n !o.object.name.toLowerCase().startsWith(notNamePrefixLower),\n );\n }\n if (\n opts.namePrefixes !== undefined &&\n (opts.namePrefix !== undefined || opts.notNamePrefix !== undefined)\n ) {\n console.error(\n `refactor list: --name-prefixes is mutually exclusive with --name-prefix and --not-name-prefix; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.namePrefixes !== undefined) {\n if (typeof opts.namePrefixes !== 'string' || opts.namePrefixes.trim().length === 0) {\n console.error(\n `refactor list: --name-prefixes must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.namePrefixes\n .split(',')\n .map((s) => s.trim().toLowerCase())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --name-prefixes must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.object?.name !== 'string') return false;\n const nameLower = o.object.name.toLowerCase();\n return parsed.some((p) => nameLower.startsWith(p));\n });\n }\n if (\n opts.notNamePrefixes !== undefined &&\n (opts.namePrefix !== undefined ||\n opts.notNamePrefix !== undefined ||\n opts.namePrefixes !== undefined)\n ) {\n console.error(\n `refactor list: --not-name-prefixes is mutually exclusive with --name-prefix, --not-name-prefix, and --name-prefixes; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notNamePrefixes !== undefined) {\n if (\n typeof opts.notNamePrefixes !== 'string' ||\n opts.notNamePrefixes.trim().length === 0\n ) {\n console.error(\n `refactor list: --not-name-prefixes must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.notNamePrefixes\n .split(',')\n .map((s) => s.trim().toLowerCase())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --not-name-prefixes must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.object?.name !== 'string') return false;\n const nameLower = o.object.name.toLowerCase();\n return !parsed.some((p) => nameLower.startsWith(p));\n });\n }\n if (opts.nameSuffix !== undefined && opts.notNameSuffix !== undefined) {\n console.error(\n `refactor list: --name-suffix and --not-name-suffix are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.nameSuffix !== undefined) {\n if (typeof opts.nameSuffix !== 'string' || opts.nameSuffix.length === 0) {\n console.error(`refactor list: --name-suffix must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const nameSuffixLower = opts.nameSuffix.toLowerCase();\n operations = operations.filter(\n (o) =>\n typeof o.object?.name === 'string' &&\n o.object.name.toLowerCase().endsWith(nameSuffixLower),\n );\n }\n if (opts.notNameSuffix !== undefined) {\n if (typeof opts.notNameSuffix !== 'string' || opts.notNameSuffix.length === 0) {\n console.error(`refactor list: --not-name-suffix must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const notNameSuffixLower = opts.notNameSuffix.toLowerCase();\n operations = operations.filter(\n (o) =>\n typeof o.object?.name === 'string' &&\n !o.object.name.toLowerCase().endsWith(notNameSuffixLower),\n );\n }\n if (\n opts.nameSuffixes !== undefined &&\n (opts.nameSuffix !== undefined || opts.notNameSuffix !== undefined)\n ) {\n console.error(\n `refactor list: --name-suffixes is mutually exclusive with --name-suffix and --not-name-suffix; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.nameSuffixes !== undefined) {\n if (typeof opts.nameSuffixes !== 'string' || opts.nameSuffixes.trim().length === 0) {\n console.error(\n `refactor list: --name-suffixes must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.nameSuffixes\n .split(',')\n .map((s) => s.trim().toLowerCase())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --name-suffixes must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.object?.name !== 'string') return false;\n const nameLower = o.object.name.toLowerCase();\n return parsed.some((s) => nameLower.endsWith(s));\n });\n }\n if (\n opts.notNameSuffixes !== undefined &&\n (opts.nameSuffix !== undefined ||\n opts.notNameSuffix !== undefined ||\n opts.nameSuffixes !== undefined)\n ) {\n console.error(\n `refactor list: --not-name-suffixes is mutually exclusive with --name-suffix, --not-name-suffix, and --name-suffixes; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notNameSuffixes !== undefined) {\n if (\n typeof opts.notNameSuffixes !== 'string' ||\n opts.notNameSuffixes.trim().length === 0\n ) {\n console.error(\n `refactor list: --not-name-suffixes must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.notNameSuffixes\n .split(',')\n .map((s) => s.trim().toLowerCase())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --not-name-suffixes must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.object?.name !== 'string') return false;\n const nameLower = o.object.name.toLowerCase();\n return !parsed.some((s) => nameLower.endsWith(s));\n });\n }\n if (opts.nameExact !== undefined && opts.notNameExact !== undefined) {\n console.error(\n `refactor list: --name-exact and --not-name-exact are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.nameExact !== undefined) {\n if (typeof opts.nameExact !== 'string' || opts.nameExact.length === 0) {\n console.error(`refactor list: --name-exact must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const nameExactLower = opts.nameExact.toLowerCase();\n operations = operations.filter(\n (o) =>\n typeof o.object?.name === 'string' && o.object.name.toLowerCase() === nameExactLower,\n );\n }\n if (opts.notNameExact !== undefined) {\n if (typeof opts.notNameExact !== 'string' || opts.notNameExact.length === 0) {\n console.error(`refactor list: --not-name-exact must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const notNameExactLower = opts.notNameExact.toLowerCase();\n operations = operations.filter(\n (o) =>\n typeof o.object?.name === 'string' &&\n o.object.name.toLowerCase() !== notNameExactLower,\n );\n }\n if (\n opts.names !== undefined &&\n (opts.nameExact !== undefined || opts.notNameExact !== undefined)\n ) {\n console.error(\n `refactor list: --names is mutually exclusive with --name-exact and --not-name-exact; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (\n opts.notNames !== undefined &&\n (opts.nameExact !== undefined ||\n opts.notNameExact !== undefined ||\n opts.names !== undefined)\n ) {\n console.error(\n `refactor list: --not-names is mutually exclusive with --name-exact, --not-name-exact, and --names; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.names !== undefined) {\n if (typeof opts.names !== 'string' || opts.names.trim().length === 0) {\n console.error(`refactor list: --names must be a non-empty comma-separated list.`);\n process.exitCode = 1;\n return;\n }\n const parsed = opts.names\n .split(',')\n .map((s) => s.trim().toLowerCase())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(`refactor list: --names must contain at least one non-empty value.`);\n process.exitCode = 1;\n return;\n }\n const wantSet = new Set(parsed);\n operations = operations.filter(\n (o) => typeof o.object?.name === 'string' && wantSet.has(o.object.name.toLowerCase()),\n );\n }\n if (opts.notNames !== undefined) {\n if (typeof opts.notNames !== 'string' || opts.notNames.trim().length === 0) {\n console.error(`refactor list: --not-names must be a non-empty comma-separated list.`);\n process.exitCode = 1;\n return;\n }\n const parsed = opts.notNames\n .split(',')\n .map((s) => s.trim().toLowerCase())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(`refactor list: --not-names must contain at least one non-empty value.`);\n process.exitCode = 1;\n return;\n }\n const excludeSet = new Set(parsed);\n operations = operations.filter(\n (o) =>\n typeof o.object?.name === 'string' && !excludeSet.has(o.object.name.toLowerCase()),\n );\n }\n if (opts.schema !== undefined && opts.notSchema !== undefined) {\n console.error(\n `refactor list: --schema and --not-schema are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.schema !== undefined) {\n if (typeof opts.schema !== 'string' || opts.schema.length === 0) {\n console.error(`refactor list: --schema must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const schemaNeedleLower = opts.schema.toLowerCase();\n operations = operations.filter(\n (o) =>\n typeof o.object?.schema === 'string' &&\n o.object.schema.toLowerCase().includes(schemaNeedleLower),\n );\n }\n if (opts.notSchema !== undefined) {\n if (typeof opts.notSchema !== 'string' || opts.notSchema.length === 0) {\n console.error(`refactor list: --not-schema must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const notSchemaNeedleLower = opts.notSchema.toLowerCase();\n operations = operations.filter(\n (o) =>\n typeof o.object?.schema === 'string' &&\n !o.object.schema.toLowerCase().includes(notSchemaNeedleLower),\n );\n }\n if (\n opts.schemaContainsAny !== undefined &&\n (opts.schema !== undefined || opts.notSchema !== undefined)\n ) {\n console.error(\n `refactor list: --schema-contains-any is mutually exclusive with --schema and --not-schema; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.schemaContainsAny !== undefined) {\n if (\n typeof opts.schemaContainsAny !== 'string' ||\n opts.schemaContainsAny.trim().length === 0\n ) {\n console.error(\n `refactor list: --schema-contains-any must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.schemaContainsAny\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --schema-contains-any must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsedLower = parsed.map((s) => s.toLowerCase());\n operations = operations.filter((o) => {\n if (typeof o.object?.schema !== 'string') return false;\n const schemaLower = o.object.schema.toLowerCase();\n return parsedLower.some((s) => schemaLower.includes(s));\n });\n }\n if (\n opts.notSchemaContainsAny !== undefined &&\n (opts.schema !== undefined ||\n opts.notSchema !== undefined ||\n opts.schemaContainsAny !== undefined)\n ) {\n console.error(\n `refactor list: --not-schema-contains-any is mutually exclusive with --schema, --not-schema, and --schema-contains-any; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notSchemaContainsAny !== undefined) {\n if (\n typeof opts.notSchemaContainsAny !== 'string' ||\n opts.notSchemaContainsAny.trim().length === 0\n ) {\n console.error(\n `refactor list: --not-schema-contains-any must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.notSchemaContainsAny\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --not-schema-contains-any must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsedLower = parsed.map((s) => s.toLowerCase());\n operations = operations.filter((o) => {\n if (typeof o.object?.schema !== 'string') return true;\n const schemaLower = o.object.schema.toLowerCase();\n return !parsedLower.some((s) => schemaLower.includes(s));\n });\n }\n if (\n opts.schemaContainsAll !== undefined &&\n (opts.schema !== undefined ||\n opts.notSchema !== undefined ||\n opts.schemaContainsAny !== undefined ||\n opts.notSchemaContainsAny !== undefined)\n ) {\n console.error(\n `refactor list: --schema-contains-all is mutually exclusive with --schema, --not-schema, --schema-contains-any, and --not-schema-contains-any; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.schemaContainsAll !== undefined) {\n if (\n typeof opts.schemaContainsAll !== 'string' ||\n opts.schemaContainsAll.trim().length === 0\n ) {\n console.error(\n `refactor list: --schema-contains-all must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.schemaContainsAll\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --schema-contains-all must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsedLower = parsed.map((s) => s.toLowerCase());\n operations = operations.filter((o) => {\n if (typeof o.object?.schema !== 'string') return false;\n const schemaLower = o.object.schema.toLowerCase();\n return parsedLower.every((s) => schemaLower.includes(s));\n });\n }\n if (\n opts.notSchemaContainsAll !== undefined &&\n (opts.schema !== undefined ||\n opts.notSchema !== undefined ||\n opts.schemaContainsAny !== undefined ||\n opts.notSchemaContainsAny !== undefined ||\n opts.schemaContainsAll !== undefined)\n ) {\n console.error(\n `refactor list: --not-schema-contains-all is mutually exclusive with --schema, --not-schema, --schema-contains-any, --not-schema-contains-any, and --schema-contains-all; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notSchemaContainsAll !== undefined) {\n if (\n typeof opts.notSchemaContainsAll !== 'string' ||\n opts.notSchemaContainsAll.trim().length === 0\n ) {\n console.error(\n `refactor list: --not-schema-contains-all must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.notSchemaContainsAll\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --not-schema-contains-all must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsedLower = parsed.map((s) => s.toLowerCase());\n operations = operations.filter((o) => {\n if (typeof o.object?.schema !== 'string') return true;\n const schemaLower = o.object.schema.toLowerCase();\n return !parsedLower.every((s) => schemaLower.includes(s));\n });\n }\n if (\n opts.schemaRegex !== undefined &&\n (opts.schema !== undefined ||\n opts.notSchema !== undefined ||\n opts.schemaContainsAny !== undefined ||\n opts.notSchemaContainsAny !== undefined ||\n opts.schemaContainsAll !== undefined ||\n opts.notSchemaContainsAll !== undefined)\n ) {\n console.error(\n `refactor list: --schema-regex is mutually exclusive with --schema, --not-schema, --schema-contains-any, --not-schema-contains-any, --schema-contains-all, and --not-schema-contains-all; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.schemaRegex !== undefined) {\n if (typeof opts.schemaRegex !== 'string' || opts.schemaRegex.length === 0) {\n console.error(`refactor list: --schema-regex must be a non-empty pattern.`);\n process.exitCode = 1;\n return;\n }\n let schemaPattern: RegExp;\n try {\n schemaPattern = new RegExp(opts.schemaRegex, 'i');\n } catch (err) {\n console.error(\n `refactor list: --schema-regex invalid regex pattern: ${(err as Error).message}`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.object?.schema !== 'string') return false;\n return schemaPattern.test(o.object.schema);\n });\n }\n if (\n opts.notSchemaRegex !== undefined &&\n (opts.schema !== undefined ||\n opts.notSchema !== undefined ||\n opts.schemaContainsAny !== undefined ||\n opts.notSchemaContainsAny !== undefined ||\n opts.schemaContainsAll !== undefined ||\n opts.notSchemaContainsAll !== undefined ||\n opts.schemaRegex !== undefined)\n ) {\n console.error(\n `refactor list: --not-schema-regex is mutually exclusive with --schema, --not-schema, --schema-contains-any, --not-schema-contains-any, --schema-contains-all, --not-schema-contains-all, and --schema-regex; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notSchemaRegex !== undefined) {\n if (typeof opts.notSchemaRegex !== 'string' || opts.notSchemaRegex.length === 0) {\n console.error(`refactor list: --not-schema-regex must be a non-empty pattern.`);\n process.exitCode = 1;\n return;\n }\n let notSchemaPattern: RegExp;\n try {\n notSchemaPattern = new RegExp(opts.notSchemaRegex, 'i');\n } catch (err) {\n console.error(\n `refactor list: --not-schema-regex invalid regex pattern: ${(err as Error).message}`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.object?.schema !== 'string') return true;\n return !notSchemaPattern.test(o.object.schema);\n });\n }\n if (opts.schemaPrefix !== undefined && opts.notSchemaPrefix !== undefined) {\n console.error(\n `refactor list: --schema-prefix and --not-schema-prefix are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.schemaPrefix !== undefined) {\n if (typeof opts.schemaPrefix !== 'string' || opts.schemaPrefix.length === 0) {\n console.error(`refactor list: --schema-prefix must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const schemaPrefixLower = opts.schemaPrefix.toLowerCase();\n operations = operations.filter(\n (o) =>\n typeof o.object?.schema === 'string' &&\n o.object.schema.toLowerCase().startsWith(schemaPrefixLower),\n );\n }\n if (opts.notSchemaPrefix !== undefined) {\n if (typeof opts.notSchemaPrefix !== 'string' || opts.notSchemaPrefix.length === 0) {\n console.error(`refactor list: --not-schema-prefix must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const notSchemaPrefixLower = opts.notSchemaPrefix.toLowerCase();\n operations = operations.filter(\n (o) =>\n typeof o.object?.schema === 'string' &&\n !o.object.schema.toLowerCase().startsWith(notSchemaPrefixLower),\n );\n }\n if (\n opts.schemaPrefixes !== undefined &&\n (opts.schemaPrefix !== undefined || opts.notSchemaPrefix !== undefined)\n ) {\n console.error(\n `refactor list: --schema-prefixes is mutually exclusive with --schema-prefix and --not-schema-prefix; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.schemaPrefixes !== undefined) {\n if (typeof opts.schemaPrefixes !== 'string' || opts.schemaPrefixes.trim().length === 0) {\n console.error(\n `refactor list: --schema-prefixes must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.schemaPrefixes\n .split(',')\n .map((s) => s.trim().toLowerCase())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --schema-prefixes must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.object?.schema !== 'string') return false;\n const schemaLower = o.object.schema.toLowerCase();\n return parsed.some((p) => schemaLower.startsWith(p));\n });\n }\n if (\n opts.notSchemaPrefixes !== undefined &&\n (opts.schemaPrefix !== undefined ||\n opts.notSchemaPrefix !== undefined ||\n opts.schemaPrefixes !== undefined)\n ) {\n console.error(\n `refactor list: --not-schema-prefixes is mutually exclusive with --schema-prefix, --not-schema-prefix, and --schema-prefixes; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notSchemaPrefixes !== undefined) {\n if (\n typeof opts.notSchemaPrefixes !== 'string' ||\n opts.notSchemaPrefixes.trim().length === 0\n ) {\n console.error(\n `refactor list: --not-schema-prefixes must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.notSchemaPrefixes\n .split(',')\n .map((s) => s.trim().toLowerCase())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --not-schema-prefixes must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.object?.schema !== 'string') return false;\n const schemaLower = o.object.schema.toLowerCase();\n return !parsed.some((p) => schemaLower.startsWith(p));\n });\n }\n if (opts.schemaSuffix !== undefined && opts.notSchemaSuffix !== undefined) {\n console.error(\n `refactor list: --schema-suffix and --not-schema-suffix are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.schemaSuffix !== undefined) {\n if (typeof opts.schemaSuffix !== 'string' || opts.schemaSuffix.length === 0) {\n console.error(`refactor list: --schema-suffix must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const schemaSuffixLower = opts.schemaSuffix.toLowerCase();\n operations = operations.filter(\n (o) =>\n typeof o.object?.schema === 'string' &&\n o.object.schema.toLowerCase().endsWith(schemaSuffixLower),\n );\n }\n if (opts.notSchemaSuffix !== undefined) {\n if (typeof opts.notSchemaSuffix !== 'string' || opts.notSchemaSuffix.length === 0) {\n console.error(`refactor list: --not-schema-suffix must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const notSchemaSuffixLower = opts.notSchemaSuffix.toLowerCase();\n operations = operations.filter(\n (o) =>\n typeof o.object?.schema === 'string' &&\n !o.object.schema.toLowerCase().endsWith(notSchemaSuffixLower),\n );\n }\n if (\n opts.schemaSuffixes !== undefined &&\n (opts.schemaSuffix !== undefined || opts.notSchemaSuffix !== undefined)\n ) {\n console.error(\n `refactor list: --schema-suffixes is mutually exclusive with --schema-suffix and --not-schema-suffix; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.schemaSuffixes !== undefined) {\n if (typeof opts.schemaSuffixes !== 'string' || opts.schemaSuffixes.trim().length === 0) {\n console.error(\n `refactor list: --schema-suffixes must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.schemaSuffixes\n .split(',')\n .map((s) => s.trim().toLowerCase())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --schema-suffixes must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.object?.schema !== 'string') return false;\n const schemaLower = o.object.schema.toLowerCase();\n return parsed.some((s) => schemaLower.endsWith(s));\n });\n }\n if (\n opts.notSchemaSuffixes !== undefined &&\n (opts.schemaSuffix !== undefined ||\n opts.notSchemaSuffix !== undefined ||\n opts.schemaSuffixes !== undefined)\n ) {\n console.error(\n `refactor list: --not-schema-suffixes is mutually exclusive with --schema-suffix, --not-schema-suffix, and --schema-suffixes; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notSchemaSuffixes !== undefined) {\n if (\n typeof opts.notSchemaSuffixes !== 'string' ||\n opts.notSchemaSuffixes.trim().length === 0\n ) {\n console.error(\n `refactor list: --not-schema-suffixes must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.notSchemaSuffixes\n .split(',')\n .map((s) => s.trim().toLowerCase())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --not-schema-suffixes must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.object?.schema !== 'string') return false;\n const schemaLower = o.object.schema.toLowerCase();\n return !parsed.some((s) => schemaLower.endsWith(s));\n });\n }\n if (opts.schemaExact !== undefined && opts.notSchemaExact !== undefined) {\n console.error(\n `refactor list: --schema-exact and --not-schema-exact are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.schemaExact !== undefined) {\n if (typeof opts.schemaExact !== 'string' || opts.schemaExact.length === 0) {\n console.error(`refactor list: --schema-exact must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const schemaExactLower = opts.schemaExact.toLowerCase();\n operations = operations.filter(\n (o) =>\n typeof o.object?.schema === 'string' &&\n o.object.schema.toLowerCase() === schemaExactLower,\n );\n }\n if (opts.notSchemaExact !== undefined) {\n if (typeof opts.notSchemaExact !== 'string' || opts.notSchemaExact.length === 0) {\n console.error(`refactor list: --not-schema-exact must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const notSchemaExactLower = opts.notSchemaExact.toLowerCase();\n operations = operations.filter(\n (o) =>\n typeof o.object?.schema === 'string' &&\n o.object.schema.toLowerCase() !== notSchemaExactLower,\n );\n }\n if (\n opts.schemas !== undefined &&\n (opts.schemaExact !== undefined || opts.notSchemaExact !== undefined)\n ) {\n console.error(\n `refactor list: --schemas is mutually exclusive with --schema-exact and --not-schema-exact; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.schemas !== undefined) {\n if (typeof opts.schemas !== 'string' || opts.schemas.trim().length === 0) {\n console.error(`refactor list: --schemas must be a non-empty comma-separated list.`);\n process.exitCode = 1;\n return;\n }\n const parsed = opts.schemas\n .split(',')\n .map((s) => s.trim().toLowerCase())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(`refactor list: --schemas must contain at least one non-empty value.`);\n process.exitCode = 1;\n return;\n }\n const wantSet = new Set(parsed);\n operations = operations.filter(\n (o) =>\n typeof o.object?.schema === 'string' && wantSet.has(o.object.schema.toLowerCase()),\n );\n }\n if (\n opts.notSchemas !== undefined &&\n (opts.schemaExact !== undefined ||\n opts.notSchemaExact !== undefined ||\n opts.schemas !== undefined)\n ) {\n console.error(\n `refactor list: --not-schemas is mutually exclusive with --schema-exact, --not-schema-exact, and --schemas; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notSchemas !== undefined) {\n if (typeof opts.notSchemas !== 'string' || opts.notSchemas.trim().length === 0) {\n console.error(`refactor list: --not-schemas must be a non-empty comma-separated list.`);\n process.exitCode = 1;\n return;\n }\n const parsed = opts.notSchemas\n .split(',')\n .map((s) => s.trim().toLowerCase())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --not-schemas must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n const excludeSet = new Set(parsed);\n operations = operations.filter(\n (o) =>\n typeof o.object?.schema === 'string' &&\n !excludeSet.has(o.object.schema.toLowerCase()),\n );\n }\n if (opts.databasePrefix !== undefined && opts.notDatabasePrefix !== undefined) {\n console.error(\n `refactor list: --database-prefix and --not-database-prefix are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.databasePrefix !== undefined) {\n if (typeof opts.databasePrefix !== 'string' || opts.databasePrefix.length === 0) {\n console.error(`refactor list: --database-prefix must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const dbPrefixLower = opts.databasePrefix.toLowerCase();\n operations = operations.filter(\n (o) =>\n typeof o.object?.database === 'string' &&\n o.object.database.toLowerCase().startsWith(dbPrefixLower),\n );\n }\n if (opts.notDatabasePrefix !== undefined) {\n if (typeof opts.notDatabasePrefix !== 'string' || opts.notDatabasePrefix.length === 0) {\n console.error(`refactor list: --not-database-prefix must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const notDbPrefixLower = opts.notDatabasePrefix.toLowerCase();\n operations = operations.filter(\n (o) =>\n typeof o.object?.database === 'string' &&\n !o.object.database.toLowerCase().startsWith(notDbPrefixLower),\n );\n }\n if (\n opts.databasePrefixes !== undefined &&\n (opts.databasePrefix !== undefined || opts.notDatabasePrefix !== undefined)\n ) {\n console.error(\n `refactor list: --database-prefixes is mutually exclusive with --database-prefix and --not-database-prefix; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.databasePrefixes !== undefined) {\n if (\n typeof opts.databasePrefixes !== 'string' ||\n opts.databasePrefixes.trim().length === 0\n ) {\n console.error(\n `refactor list: --database-prefixes must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.databasePrefixes\n .split(',')\n .map((s) => s.trim().toLowerCase())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --database-prefixes must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.object?.database !== 'string') return false;\n const dbLower = o.object.database.toLowerCase();\n return parsed.some((p) => dbLower.startsWith(p));\n });\n }\n if (\n opts.notDatabasePrefixes !== undefined &&\n (opts.databasePrefix !== undefined ||\n opts.notDatabasePrefix !== undefined ||\n opts.databasePrefixes !== undefined)\n ) {\n console.error(\n `refactor list: --not-database-prefixes is mutually exclusive with --database-prefix, --not-database-prefix, and --database-prefixes; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notDatabasePrefixes !== undefined) {\n if (\n typeof opts.notDatabasePrefixes !== 'string' ||\n opts.notDatabasePrefixes.trim().length === 0\n ) {\n console.error(\n `refactor list: --not-database-prefixes must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.notDatabasePrefixes\n .split(',')\n .map((s) => s.trim().toLowerCase())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --not-database-prefixes must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.object?.database !== 'string') return false;\n const dbLower = o.object.database.toLowerCase();\n return !parsed.some((p) => dbLower.startsWith(p));\n });\n }\n if (opts.databaseSuffix !== undefined && opts.notDatabaseSuffix !== undefined) {\n console.error(\n `refactor list: --database-suffix and --not-database-suffix are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.databaseSuffix !== undefined) {\n if (typeof opts.databaseSuffix !== 'string' || opts.databaseSuffix.length === 0) {\n console.error(`refactor list: --database-suffix must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const dbSuffixLower = opts.databaseSuffix.toLowerCase();\n operations = operations.filter(\n (o) =>\n typeof o.object?.database === 'string' &&\n o.object.database.toLowerCase().endsWith(dbSuffixLower),\n );\n }\n if (opts.notDatabaseSuffix !== undefined) {\n if (typeof opts.notDatabaseSuffix !== 'string' || opts.notDatabaseSuffix.length === 0) {\n console.error(`refactor list: --not-database-suffix must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const notDbSuffixLower = opts.notDatabaseSuffix.toLowerCase();\n operations = operations.filter(\n (o) =>\n typeof o.object?.database === 'string' &&\n !o.object.database.toLowerCase().endsWith(notDbSuffixLower),\n );\n }\n if (\n opts.databaseSuffixes !== undefined &&\n (opts.databaseSuffix !== undefined || opts.notDatabaseSuffix !== undefined)\n ) {\n console.error(\n `refactor list: --database-suffixes is mutually exclusive with --database-suffix and --not-database-suffix; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.databaseSuffixes !== undefined) {\n if (\n typeof opts.databaseSuffixes !== 'string' ||\n opts.databaseSuffixes.trim().length === 0\n ) {\n console.error(\n `refactor list: --database-suffixes must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.databaseSuffixes\n .split(',')\n .map((s) => s.trim().toLowerCase())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --database-suffixes must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.object?.database !== 'string') return false;\n const dbLower = o.object.database.toLowerCase();\n return parsed.some((s) => dbLower.endsWith(s));\n });\n }\n if (\n opts.notDatabaseSuffixes !== undefined &&\n (opts.databaseSuffix !== undefined ||\n opts.notDatabaseSuffix !== undefined ||\n opts.databaseSuffixes !== undefined)\n ) {\n console.error(\n `refactor list: --not-database-suffixes is mutually exclusive with --database-suffix, --not-database-suffix, and --database-suffixes; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notDatabaseSuffixes !== undefined) {\n if (\n typeof opts.notDatabaseSuffixes !== 'string' ||\n opts.notDatabaseSuffixes.trim().length === 0\n ) {\n console.error(\n `refactor list: --not-database-suffixes must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.notDatabaseSuffixes\n .split(',')\n .map((s) => s.trim().toLowerCase())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --not-database-suffixes must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.object?.database !== 'string') return false;\n const dbLower = o.object.database.toLowerCase();\n return !parsed.some((s) => dbLower.endsWith(s));\n });\n }\n if (opts.databaseExact !== undefined && opts.notDatabaseExact !== undefined) {\n console.error(\n `refactor list: --database-exact and --not-database-exact are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.databaseExact !== undefined) {\n if (typeof opts.databaseExact !== 'string' || opts.databaseExact.length === 0) {\n console.error(`refactor list: --database-exact must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const dbExactLower = opts.databaseExact.toLowerCase();\n operations = operations.filter(\n (o) =>\n typeof o.object?.database === 'string' &&\n o.object.database.toLowerCase() === dbExactLower,\n );\n }\n if (opts.notDatabaseExact !== undefined) {\n if (typeof opts.notDatabaseExact !== 'string' || opts.notDatabaseExact.length === 0) {\n console.error(`refactor list: --not-database-exact must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const notDbExactLower = opts.notDatabaseExact.toLowerCase();\n operations = operations.filter(\n (o) =>\n typeof o.object?.database === 'string' &&\n o.object.database.toLowerCase() !== notDbExactLower,\n );\n }\n if (\n opts.databases !== undefined &&\n (opts.databaseExact !== undefined || opts.notDatabaseExact !== undefined)\n ) {\n console.error(\n `refactor list: --databases is mutually exclusive with --database-exact and --not-database-exact; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.databases !== undefined) {\n if (typeof opts.databases !== 'string' || opts.databases.trim().length === 0) {\n console.error(`refactor list: --databases must be a non-empty comma-separated list.`);\n process.exitCode = 1;\n return;\n }\n const parsed = opts.databases\n .split(',')\n .map((s) => s.trim().toLowerCase())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(`refactor list: --databases must contain at least one non-empty value.`);\n process.exitCode = 1;\n return;\n }\n const wantSet = new Set(parsed);\n operations = operations.filter(\n (o) =>\n typeof o.object?.database === 'string' &&\n wantSet.has(o.object.database.toLowerCase()),\n );\n }\n if (\n opts.notDatabases !== undefined &&\n (opts.databaseExact !== undefined ||\n opts.notDatabaseExact !== undefined ||\n opts.databases !== undefined)\n ) {\n console.error(\n `refactor list: --not-databases is mutually exclusive with --database-exact, --not-database-exact, and --databases; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notDatabases !== undefined) {\n if (typeof opts.notDatabases !== 'string' || opts.notDatabases.trim().length === 0) {\n console.error(\n `refactor list: --not-databases must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.notDatabases\n .split(',')\n .map((s) => s.trim().toLowerCase())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --not-databases must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n const excludeSet = new Set(parsed);\n operations = operations.filter(\n (o) =>\n typeof o.object?.database === 'string' &&\n !excludeSet.has(o.object.database.toLowerCase()),\n );\n }\n if (opts.database !== undefined && opts.notDatabase !== undefined) {\n console.error(\n `refactor list: --database and --not-database are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.database !== undefined) {\n if (typeof opts.database !== 'string' || opts.database.length === 0) {\n console.error(`refactor list: --database must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const dbNeedleLower = opts.database.toLowerCase();\n operations = operations.filter(\n (o) =>\n typeof o.object?.database === 'string' &&\n o.object.database.toLowerCase().includes(dbNeedleLower),\n );\n }\n if (opts.notDatabase !== undefined) {\n if (typeof opts.notDatabase !== 'string' || opts.notDatabase.length === 0) {\n console.error(`refactor list: --not-database must be a non-empty string.`);\n process.exitCode = 1;\n return;\n }\n const notDbNeedleLower = opts.notDatabase.toLowerCase();\n operations = operations.filter(\n (o) =>\n typeof o.object?.database === 'string' &&\n !o.object.database.toLowerCase().includes(notDbNeedleLower),\n );\n }\n if (\n opts.databaseContainsAny !== undefined &&\n (opts.database !== undefined || opts.notDatabase !== undefined)\n ) {\n console.error(\n `refactor list: --database-contains-any is mutually exclusive with --database and --not-database; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.databaseContainsAny !== undefined) {\n if (\n typeof opts.databaseContainsAny !== 'string' ||\n opts.databaseContainsAny.trim().length === 0\n ) {\n console.error(\n `refactor list: --database-contains-any must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.databaseContainsAny\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --database-contains-any must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsedLower = parsed.map((s) => s.toLowerCase());\n operations = operations.filter((o) => {\n if (typeof o.object?.database !== 'string') return false;\n const databaseLower = o.object.database.toLowerCase();\n return parsedLower.some((s) => databaseLower.includes(s));\n });\n }\n if (\n opts.notDatabaseContainsAny !== undefined &&\n (opts.database !== undefined ||\n opts.notDatabase !== undefined ||\n opts.databaseContainsAny !== undefined)\n ) {\n console.error(\n `refactor list: --not-database-contains-any is mutually exclusive with --database, --not-database, and --database-contains-any; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notDatabaseContainsAny !== undefined) {\n if (\n typeof opts.notDatabaseContainsAny !== 'string' ||\n opts.notDatabaseContainsAny.trim().length === 0\n ) {\n console.error(\n `refactor list: --not-database-contains-any must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.notDatabaseContainsAny\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --not-database-contains-any must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsedLower = parsed.map((s) => s.toLowerCase());\n operations = operations.filter((o) => {\n if (typeof o.object?.database !== 'string') return true;\n const databaseLower = o.object.database.toLowerCase();\n return !parsedLower.some((s) => databaseLower.includes(s));\n });\n }\n if (\n opts.databaseContainsAll !== undefined &&\n (opts.database !== undefined ||\n opts.notDatabase !== undefined ||\n opts.databaseContainsAny !== undefined ||\n opts.notDatabaseContainsAny !== undefined)\n ) {\n console.error(\n `refactor list: --database-contains-all is mutually exclusive with --database, --not-database, --database-contains-any, and --not-database-contains-any; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.databaseContainsAll !== undefined) {\n if (\n typeof opts.databaseContainsAll !== 'string' ||\n opts.databaseContainsAll.trim().length === 0\n ) {\n console.error(\n `refactor list: --database-contains-all must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.databaseContainsAll\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --database-contains-all must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsedLower = parsed.map((s) => s.toLowerCase());\n operations = operations.filter((o) => {\n if (typeof o.object?.database !== 'string') return false;\n const databaseLower = o.object.database.toLowerCase();\n return parsedLower.every((s) => databaseLower.includes(s));\n });\n }\n if (\n opts.notDatabaseContainsAll !== undefined &&\n (opts.database !== undefined ||\n opts.notDatabase !== undefined ||\n opts.databaseContainsAny !== undefined ||\n opts.notDatabaseContainsAny !== undefined ||\n opts.databaseContainsAll !== undefined)\n ) {\n console.error(\n `refactor list: --not-database-contains-all is mutually exclusive with --database, --not-database, --database-contains-any, --not-database-contains-any, and --database-contains-all; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notDatabaseContainsAll !== undefined) {\n if (\n typeof opts.notDatabaseContainsAll !== 'string' ||\n opts.notDatabaseContainsAll.trim().length === 0\n ) {\n console.error(\n `refactor list: --not-database-contains-all must be a non-empty comma-separated list.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsed = opts.notDatabaseContainsAll\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parsed.length === 0) {\n console.error(\n `refactor list: --not-database-contains-all must contain at least one non-empty value.`,\n );\n process.exitCode = 1;\n return;\n }\n const parsedLower = parsed.map((s) => s.toLowerCase());\n operations = operations.filter((o) => {\n if (typeof o.object?.database !== 'string') return true;\n const databaseLower = o.object.database.toLowerCase();\n return !parsedLower.every((s) => databaseLower.includes(s));\n });\n }\n if (\n opts.databaseRegex !== undefined &&\n (opts.database !== undefined ||\n opts.notDatabase !== undefined ||\n opts.databaseContainsAny !== undefined ||\n opts.notDatabaseContainsAny !== undefined ||\n opts.databaseContainsAll !== undefined ||\n opts.notDatabaseContainsAll !== undefined)\n ) {\n console.error(\n `refactor list: --database-regex is mutually exclusive with --database, --not-database, --database-contains-any, --not-database-contains-any, --database-contains-all, and --not-database-contains-all; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.databaseRegex !== undefined) {\n if (typeof opts.databaseRegex !== 'string' || opts.databaseRegex.length === 0) {\n console.error(`refactor list: --database-regex must be a non-empty pattern.`);\n process.exitCode = 1;\n return;\n }\n let databasePattern: RegExp;\n try {\n databasePattern = new RegExp(opts.databaseRegex, 'i');\n } catch (err) {\n console.error(\n `refactor list: --database-regex invalid regex pattern: ${(err as Error).message}`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.object?.database !== 'string') return false;\n return databasePattern.test(o.object.database);\n });\n }\n if (\n opts.notDatabaseRegex !== undefined &&\n (opts.database !== undefined ||\n opts.notDatabase !== undefined ||\n opts.databaseContainsAny !== undefined ||\n opts.notDatabaseContainsAny !== undefined ||\n opts.databaseContainsAll !== undefined ||\n opts.notDatabaseContainsAll !== undefined ||\n opts.databaseRegex !== undefined)\n ) {\n console.error(\n `refactor list: --not-database-regex is mutually exclusive with --database, --not-database, --database-contains-any, --not-database-contains-any, --database-contains-all, --not-database-contains-all, and --database-regex; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notDatabaseRegex !== undefined) {\n if (typeof opts.notDatabaseRegex !== 'string' || opts.notDatabaseRegex.length === 0) {\n console.error(`refactor list: --not-database-regex must be a non-empty pattern.`);\n process.exitCode = 1;\n return;\n }\n let notDatabasePattern: RegExp;\n try {\n notDatabasePattern = new RegExp(opts.notDatabaseRegex, 'i');\n } catch (err) {\n console.error(\n `refactor list: --not-database-regex invalid regex pattern: ${(err as Error).message}`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.filter((o) => {\n if (typeof o.object?.database !== 'string') return true;\n return !notDatabasePattern.test(o.object.database);\n });\n }\n if (opts.nameMinLength !== undefined) {\n if (\n !Number.isFinite(opts.nameMinLength) ||\n !Number.isInteger(opts.nameMinLength) ||\n opts.nameMinLength < 0\n ) {\n console.error(\n `refactor list: --name-min-length ${JSON.stringify(opts.nameMinLength)} must be a non-negative integer.`,\n );\n process.exitCode = 1;\n return;\n }\n const min = opts.nameMinLength;\n operations = operations.filter(\n (o) => typeof o.object?.name === 'string' && o.object.name.length >= min,\n );\n }\n if (opts.nameMaxLength !== undefined) {\n if (\n !Number.isFinite(opts.nameMaxLength) ||\n !Number.isInteger(opts.nameMaxLength) ||\n opts.nameMaxLength < 0\n ) {\n console.error(\n `refactor list: --name-max-length ${JSON.stringify(opts.nameMaxLength)} must be a non-negative integer.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.nameMinLength !== undefined && opts.nameMinLength > opts.nameMaxLength) {\n console.error(\n `refactor list: --name-min-length ${opts.nameMinLength} is greater than --name-max-length ${opts.nameMaxLength}; range is empty by definition.`,\n );\n process.exitCode = 1;\n return;\n }\n const max = opts.nameMaxLength;\n operations = operations.filter(\n (o) => typeof o.object?.name === 'string' && o.object.name.length <= max,\n );\n }\n if (opts.schemaMinLength !== undefined) {\n if (\n !Number.isFinite(opts.schemaMinLength) ||\n !Number.isInteger(opts.schemaMinLength) ||\n opts.schemaMinLength < 0\n ) {\n console.error(\n `refactor list: --schema-min-length ${JSON.stringify(opts.schemaMinLength)} must be a non-negative integer.`,\n );\n process.exitCode = 1;\n return;\n }\n const min = opts.schemaMinLength;\n operations = operations.filter(\n (o) => typeof o.object?.schema === 'string' && o.object.schema.length >= min,\n );\n }\n if (opts.schemaMaxLength !== undefined) {\n if (\n !Number.isFinite(opts.schemaMaxLength) ||\n !Number.isInteger(opts.schemaMaxLength) ||\n opts.schemaMaxLength < 0\n ) {\n console.error(\n `refactor list: --schema-max-length ${JSON.stringify(opts.schemaMaxLength)} must be a non-negative integer.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.schemaMinLength !== undefined && opts.schemaMinLength > opts.schemaMaxLength) {\n console.error(\n `refactor list: --schema-min-length ${opts.schemaMinLength} is greater than --schema-max-length ${opts.schemaMaxLength}; range is empty by definition.`,\n );\n process.exitCode = 1;\n return;\n }\n const max = opts.schemaMaxLength;\n operations = operations.filter(\n (o) => typeof o.object?.schema === 'string' && o.object.schema.length <= max,\n );\n }\n if (opts.databaseMinLength !== undefined) {\n if (\n !Number.isFinite(opts.databaseMinLength) ||\n !Number.isInteger(opts.databaseMinLength) ||\n opts.databaseMinLength < 0\n ) {\n console.error(\n `refactor list: --database-min-length ${JSON.stringify(opts.databaseMinLength)} must be a non-negative integer.`,\n );\n process.exitCode = 1;\n return;\n }\n const min = opts.databaseMinLength;\n operations = operations.filter(\n (o) => typeof o.object?.database === 'string' && o.object.database.length >= min,\n );\n }\n if (opts.databaseMaxLength !== undefined) {\n if (\n !Number.isFinite(opts.databaseMaxLength) ||\n !Number.isInteger(opts.databaseMaxLength) ||\n opts.databaseMaxLength < 0\n ) {\n console.error(\n `refactor list: --database-max-length ${JSON.stringify(opts.databaseMaxLength)} must be a non-negative integer.`,\n );\n process.exitCode = 1;\n return;\n }\n if (\n opts.databaseMinLength !== undefined &&\n opts.databaseMinLength > opts.databaseMaxLength\n ) {\n console.error(\n `refactor list: --database-min-length ${opts.databaseMinLength} is greater than --database-max-length ${opts.databaseMaxLength}; range is empty by definition.`,\n );\n process.exitCode = 1;\n return;\n }\n const max = opts.databaseMaxLength;\n operations = operations.filter(\n (o) => typeof o.object?.database === 'string' && o.object.database.length <= max,\n );\n }\n if (opts.noteMinLength !== undefined) {\n if (\n !Number.isFinite(opts.noteMinLength) ||\n !Number.isInteger(opts.noteMinLength) ||\n opts.noteMinLength < 0\n ) {\n console.error(\n `refactor list: --note-min-length ${JSON.stringify(opts.noteMinLength)} must be a non-negative integer.`,\n );\n process.exitCode = 1;\n return;\n }\n const min = opts.noteMinLength;\n operations = operations.filter((o) => typeof o.note === 'string' && o.note.length >= min);\n }\n if (opts.noteMaxLength !== undefined) {\n if (\n !Number.isFinite(opts.noteMaxLength) ||\n !Number.isInteger(opts.noteMaxLength) ||\n opts.noteMaxLength < 0\n ) {\n console.error(\n `refactor list: --note-max-length ${JSON.stringify(opts.noteMaxLength)} must be a non-negative integer.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.noteMinLength !== undefined && opts.noteMinLength > opts.noteMaxLength) {\n console.error(\n `refactor list: --note-min-length ${opts.noteMinLength} is greater than --note-max-length ${opts.noteMaxLength}; range is empty by definition.`,\n );\n process.exitCode = 1;\n return;\n }\n const max = opts.noteMaxLength;\n operations = operations.filter((o) => typeof o.note === 'string' && o.note.length <= max);\n }\n if (opts.idMinLength !== undefined) {\n if (\n !Number.isFinite(opts.idMinLength) ||\n !Number.isInteger(opts.idMinLength) ||\n opts.idMinLength < 0\n ) {\n console.error(\n `refactor list: --id-min-length ${JSON.stringify(opts.idMinLength)} must be a non-negative integer.`,\n );\n process.exitCode = 1;\n return;\n }\n const min = opts.idMinLength;\n operations = operations.filter((o) => typeof o.id === 'string' && o.id.length >= min);\n }\n if (opts.idMaxLength !== undefined) {\n if (\n !Number.isFinite(opts.idMaxLength) ||\n !Number.isInteger(opts.idMaxLength) ||\n opts.idMaxLength < 0\n ) {\n console.error(\n `refactor list: --id-max-length ${JSON.stringify(opts.idMaxLength)} must be a non-negative integer.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.idMinLength !== undefined && opts.idMinLength > opts.idMaxLength) {\n console.error(\n `refactor list: --id-min-length ${opts.idMinLength} is greater than --id-max-length ${opts.idMaxLength}; range is empty by definition.`,\n );\n process.exitCode = 1;\n return;\n }\n const max = opts.idMaxLength;\n operations = operations.filter((o) => typeof o.id === 'string' && o.id.length <= max);\n }\n if (opts.hasDatabase && opts.missingDatabase) {\n console.error(\n `refactor list: --has-database and --missing-database are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.hasDatabase) {\n operations = operations.filter(\n (o) => typeof o.object?.database === 'string' && o.object.database.length > 0,\n );\n }\n if (opts.missingDatabase) {\n operations = operations.filter(\n (o) => typeof o.object?.database !== 'string' || o.object.database.length === 0,\n );\n }\n if (opts.hasSchema && opts.missingSchema) {\n console.error(\n `refactor list: --has-schema and --missing-schema are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.hasSchema) {\n operations = operations.filter(\n (o) => typeof o.object?.schema === 'string' && o.object.schema.length > 0,\n );\n }\n if (opts.missingSchema) {\n operations = operations.filter(\n (o) => typeof o.object?.schema !== 'string' || o.object.schema.length === 0,\n );\n }\n if (opts.hasNote && opts.missingNote) {\n console.error(\n `refactor list: --has-note and --missing-note are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.hasNote) {\n operations = operations.filter((o) => typeof o.note === 'string' && o.note.length > 0);\n }\n if (opts.missingNote) {\n operations = operations.filter((o) => typeof o.note !== 'string' || o.note.length === 0);\n }\n if (opts.last !== undefined && opts.first !== undefined) {\n console.error(`refactor list: --first and --last are mutually exclusive; pick one.`);\n process.exitCode = 1;\n return;\n }\n if (opts.last !== undefined) {\n if (!Number.isFinite(opts.last) || opts.last <= 0) {\n console.error(\n `refactor list: --last ${JSON.stringify(opts.last)} must be a positive integer.`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.slice(-opts.last);\n }\n if (opts.first !== undefined) {\n if (!Number.isFinite(opts.first) || opts.first <= 0) {\n console.error(\n `refactor list: --first ${JSON.stringify(opts.first)} must be a positive integer.`,\n );\n process.exitCode = 1;\n return;\n }\n operations = operations.slice(0, opts.first);\n }\n if (opts.year !== undefined && opts.years !== undefined) {\n console.error(`refactor list: --year and --years are mutually exclusive; pick one.`);\n process.exitCode = 1;\n return;\n }\n if (opts.year !== undefined) {\n if (!Number.isFinite(opts.year) || !Number.isInteger(opts.year) || opts.year < 0) {\n console.error(\n `refactor list: --year ${JSON.stringify(opts.year)} must be a non-negative integer.`,\n );\n process.exitCode = 1;\n return;\n }\n const year = opts.year;\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return false;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return false;\n return d.getUTCFullYear() === year;\n });\n }\n if (opts.years !== undefined) {\n const parts = opts.years\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parts.length === 0) {\n console.error(`refactor list: --years requires at least one year value.`);\n process.exitCode = 1;\n return;\n }\n const years: number[] = [];\n for (const p of parts) {\n const n = Number(p);\n if (!Number.isFinite(n) || !Number.isInteger(n) || n < 0) {\n console.error(\n `refactor list: --years entry ${JSON.stringify(p)} must be a non-negative integer.`,\n );\n process.exitCode = 1;\n return;\n }\n years.push(n);\n }\n const yearSet = new Set(years);\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return false;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return false;\n return yearSet.has(d.getUTCFullYear());\n });\n }\n if (opts.notYear !== undefined && (opts.year !== undefined || opts.years !== undefined)) {\n console.error(\n `refactor list: --not-year is mutually exclusive with --year and --years; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notYear !== undefined) {\n if (\n !Number.isFinite(opts.notYear) ||\n !Number.isInteger(opts.notYear) ||\n opts.notYear < 0\n ) {\n console.error(\n `refactor list: --not-year ${JSON.stringify(opts.notYear)} must be a non-negative integer.`,\n );\n process.exitCode = 1;\n return;\n }\n const year = opts.notYear;\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return true;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return true;\n return d.getUTCFullYear() !== year;\n });\n }\n if (\n opts.notYears !== undefined &&\n (opts.year !== undefined || opts.years !== undefined || opts.notYear !== undefined)\n ) {\n console.error(\n `refactor list: --not-years is mutually exclusive with --year, --years, and --not-year; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notYears !== undefined) {\n const parts = opts.notYears\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parts.length === 0) {\n console.error(`refactor list: --not-years requires at least one year value.`);\n process.exitCode = 1;\n return;\n }\n const years: number[] = [];\n for (const p of parts) {\n const n = Number(p);\n if (!Number.isFinite(n) || !Number.isInteger(n) || n < 0) {\n console.error(\n `refactor list: --not-years entry ${JSON.stringify(p)} must be a non-negative integer.`,\n );\n process.exitCode = 1;\n return;\n }\n years.push(n);\n }\n const yearSet = new Set(years);\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return true;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return true;\n return !yearSet.has(d.getUTCFullYear());\n });\n }\n if (opts.month !== undefined && opts.months !== undefined) {\n console.error(`refactor list: --month and --months are mutually exclusive; pick one.`);\n process.exitCode = 1;\n return;\n }\n if (opts.month !== undefined) {\n if (\n !Number.isFinite(opts.month) ||\n !Number.isInteger(opts.month) ||\n opts.month < 1 ||\n opts.month > 12\n ) {\n console.error(\n `refactor list: --month ${JSON.stringify(opts.month)} must be an integer in [1, 12].`,\n );\n process.exitCode = 1;\n return;\n }\n const monthIndex = opts.month - 1;\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return false;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return false;\n return d.getUTCMonth() === monthIndex;\n });\n }\n if (opts.months !== undefined) {\n const parts = opts.months\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parts.length === 0) {\n console.error(`refactor list: --months requires at least one month value.`);\n process.exitCode = 1;\n return;\n }\n const monthIndexes: number[] = [];\n for (const p of parts) {\n const n = Number(p);\n if (!Number.isFinite(n) || !Number.isInteger(n) || n < 1 || n > 12) {\n console.error(\n `refactor list: --months entry ${JSON.stringify(p)} must be an integer in [1, 12].`,\n );\n process.exitCode = 1;\n return;\n }\n monthIndexes.push(n - 1);\n }\n const monthSet = new Set(monthIndexes);\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return false;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return false;\n return monthSet.has(d.getUTCMonth());\n });\n }\n if (\n opts.notMonth !== undefined &&\n (opts.month !== undefined || opts.months !== undefined)\n ) {\n console.error(\n `refactor list: --not-month is mutually exclusive with --month and --months; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notMonth !== undefined) {\n if (\n !Number.isFinite(opts.notMonth) ||\n !Number.isInteger(opts.notMonth) ||\n opts.notMonth < 1 ||\n opts.notMonth > 12\n ) {\n console.error(\n `refactor list: --not-month ${JSON.stringify(opts.notMonth)} must be an integer in [1, 12].`,\n );\n process.exitCode = 1;\n return;\n }\n const monthIndex = opts.notMonth - 1;\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return true;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return true;\n return d.getUTCMonth() !== monthIndex;\n });\n }\n if (\n opts.notMonths !== undefined &&\n (opts.month !== undefined || opts.months !== undefined || opts.notMonth !== undefined)\n ) {\n console.error(\n `refactor list: --not-months is mutually exclusive with --month, --months, and --not-month; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notMonths !== undefined) {\n const parts = opts.notMonths\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parts.length === 0) {\n console.error(`refactor list: --not-months requires at least one month value.`);\n process.exitCode = 1;\n return;\n }\n const monthIndexes: number[] = [];\n for (const p of parts) {\n const n = Number(p);\n if (!Number.isFinite(n) || !Number.isInteger(n) || n < 1 || n > 12) {\n console.error(\n `refactor list: --not-months entry ${JSON.stringify(p)} must be an integer in [1, 12].`,\n );\n process.exitCode = 1;\n return;\n }\n monthIndexes.push(n - 1);\n }\n const monthSet = new Set(monthIndexes);\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return true;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return true;\n return !monthSet.has(d.getUTCMonth());\n });\n }\n if (opts.dayOfWeek !== undefined && opts.daysOfWeek !== undefined) {\n console.error(\n `refactor list: --day-of-week and --days-of-week are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.dayOfWeek !== undefined) {\n if (\n !Number.isFinite(opts.dayOfWeek) ||\n !Number.isInteger(opts.dayOfWeek) ||\n opts.dayOfWeek < 0 ||\n opts.dayOfWeek > 6\n ) {\n console.error(\n `refactor list: --day-of-week ${JSON.stringify(opts.dayOfWeek)} must be an integer in [0, 6].`,\n );\n process.exitCode = 1;\n return;\n }\n const dow = opts.dayOfWeek;\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return false;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return false;\n return d.getUTCDay() === dow;\n });\n }\n if (opts.daysOfWeek !== undefined) {\n const parts = opts.daysOfWeek\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parts.length === 0) {\n console.error(`refactor list: --days-of-week requires at least one day value.`);\n process.exitCode = 1;\n return;\n }\n const dows: number[] = [];\n for (const p of parts) {\n const n = Number(p);\n if (!Number.isFinite(n) || !Number.isInteger(n) || n < 0 || n > 6) {\n console.error(\n `refactor list: --days-of-week entry ${JSON.stringify(p)} must be an integer in [0, 6].`,\n );\n process.exitCode = 1;\n return;\n }\n dows.push(n);\n }\n const dowSet = new Set(dows);\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return false;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return false;\n return dowSet.has(d.getUTCDay());\n });\n }\n if (\n opts.notDayOfWeek !== undefined &&\n (opts.dayOfWeek !== undefined || opts.daysOfWeek !== undefined)\n ) {\n console.error(\n `refactor list: --not-day-of-week is mutually exclusive with --day-of-week and --days-of-week; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notDayOfWeek !== undefined) {\n if (\n !Number.isFinite(opts.notDayOfWeek) ||\n !Number.isInteger(opts.notDayOfWeek) ||\n opts.notDayOfWeek < 0 ||\n opts.notDayOfWeek > 6\n ) {\n console.error(\n `refactor list: --not-day-of-week ${JSON.stringify(opts.notDayOfWeek)} must be an integer in [0, 6].`,\n );\n process.exitCode = 1;\n return;\n }\n const dow = opts.notDayOfWeek;\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return true;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return true;\n return d.getUTCDay() !== dow;\n });\n }\n if (\n opts.notDaysOfWeek !== undefined &&\n (opts.dayOfWeek !== undefined ||\n opts.daysOfWeek !== undefined ||\n opts.notDayOfWeek !== undefined)\n ) {\n console.error(\n `refactor list: --not-days-of-week is mutually exclusive with --day-of-week, --days-of-week, and --not-day-of-week; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notDaysOfWeek !== undefined) {\n const parts = opts.notDaysOfWeek\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parts.length === 0) {\n console.error(`refactor list: --not-days-of-week requires at least one day value.`);\n process.exitCode = 1;\n return;\n }\n const dows: number[] = [];\n for (const p of parts) {\n const n = Number(p);\n if (!Number.isFinite(n) || !Number.isInteger(n) || n < 0 || n > 6) {\n console.error(\n `refactor list: --not-days-of-week entry ${JSON.stringify(p)} must be an integer in [0, 6].`,\n );\n process.exitCode = 1;\n return;\n }\n dows.push(n);\n }\n const dowSet = new Set(dows);\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return true;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return true;\n return !dowSet.has(d.getUTCDay());\n });\n }\n if (opts.hour !== undefined) {\n if (\n !Number.isFinite(opts.hour) ||\n !Number.isInteger(opts.hour) ||\n opts.hour < 0 ||\n opts.hour > 23\n ) {\n console.error(\n `refactor list: --hour ${JSON.stringify(opts.hour)} must be an integer in [0, 23].`,\n );\n process.exitCode = 1;\n return;\n }\n const hr = opts.hour;\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return false;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return false;\n return d.getUTCHours() === hr;\n });\n }\n if (opts.hour !== undefined && opts.hours !== undefined) {\n console.error(`refactor list: --hour and --hours are mutually exclusive; pick one.`);\n process.exitCode = 1;\n return;\n }\n if (opts.hours !== undefined) {\n const parts = opts.hours\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parts.length === 0) {\n console.error(`refactor list: --hours requires at least one hour value.`);\n process.exitCode = 1;\n return;\n }\n const hours: number[] = [];\n for (const p of parts) {\n const n = Number(p);\n if (!Number.isFinite(n) || !Number.isInteger(n) || n < 0 || n > 23) {\n console.error(\n `refactor list: --hours entry ${JSON.stringify(p)} must be an integer in [0, 23].`,\n );\n process.exitCode = 1;\n return;\n }\n hours.push(n);\n }\n const hourSet = new Set(hours);\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return false;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return false;\n return hourSet.has(d.getUTCHours());\n });\n }\n if (opts.notHour !== undefined && (opts.hour !== undefined || opts.hours !== undefined)) {\n console.error(\n `refactor list: --not-hour is mutually exclusive with --hour and --hours; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notHour !== undefined) {\n if (\n !Number.isFinite(opts.notHour) ||\n !Number.isInteger(opts.notHour) ||\n opts.notHour < 0 ||\n opts.notHour > 23\n ) {\n console.error(\n `refactor list: --not-hour ${JSON.stringify(opts.notHour)} must be an integer in [0, 23].`,\n );\n process.exitCode = 1;\n return;\n }\n const hr = opts.notHour;\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return true;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return true;\n return d.getUTCHours() !== hr;\n });\n }\n if (\n opts.notHours !== undefined &&\n (opts.hour !== undefined || opts.hours !== undefined || opts.notHour !== undefined)\n ) {\n console.error(\n `refactor list: --not-hours is mutually exclusive with --hour, --hours, and --not-hour; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notHours !== undefined) {\n const parts = opts.notHours\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parts.length === 0) {\n console.error(`refactor list: --not-hours requires at least one hour value.`);\n process.exitCode = 1;\n return;\n }\n const hours: number[] = [];\n for (const p of parts) {\n const n = Number(p);\n if (!Number.isFinite(n) || !Number.isInteger(n) || n < 0 || n > 23) {\n console.error(\n `refactor list: --not-hours entry ${JSON.stringify(p)} must be an integer in [0, 23].`,\n );\n process.exitCode = 1;\n return;\n }\n hours.push(n);\n }\n const hourSet = new Set(hours);\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return true;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return true;\n return !hourSet.has(d.getUTCHours());\n });\n }\n if (opts.minute !== undefined) {\n if (\n !Number.isFinite(opts.minute) ||\n !Number.isInteger(opts.minute) ||\n opts.minute < 0 ||\n opts.minute > 59\n ) {\n console.error(\n `refactor list: --minute ${JSON.stringify(opts.minute)} must be an integer in [0, 59].`,\n );\n process.exitCode = 1;\n return;\n }\n const mn = opts.minute;\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return false;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return false;\n return d.getUTCMinutes() === mn;\n });\n }\n if (opts.minute !== undefined && opts.minutes !== undefined) {\n console.error(`refactor list: --minute and --minutes are mutually exclusive; pick one.`);\n process.exitCode = 1;\n return;\n }\n if (opts.minutes !== undefined) {\n const parts = opts.minutes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parts.length === 0) {\n console.error(`refactor list: --minutes requires at least one minute value.`);\n process.exitCode = 1;\n return;\n }\n const minutes: number[] = [];\n for (const p of parts) {\n const n = Number(p);\n if (!Number.isFinite(n) || !Number.isInteger(n) || n < 0 || n > 59) {\n console.error(\n `refactor list: --minutes entry ${JSON.stringify(p)} must be an integer in [0, 59].`,\n );\n process.exitCode = 1;\n return;\n }\n minutes.push(n);\n }\n const minuteSet = new Set(minutes);\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return false;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return false;\n return minuteSet.has(d.getUTCMinutes());\n });\n }\n if (\n opts.notMinute !== undefined &&\n (opts.minute !== undefined || opts.minutes !== undefined)\n ) {\n console.error(\n `refactor list: --not-minute is mutually exclusive with --minute and --minutes; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notMinute !== undefined) {\n if (\n !Number.isFinite(opts.notMinute) ||\n !Number.isInteger(opts.notMinute) ||\n opts.notMinute < 0 ||\n opts.notMinute > 59\n ) {\n console.error(\n `refactor list: --not-minute ${JSON.stringify(opts.notMinute)} must be an integer in [0, 59].`,\n );\n process.exitCode = 1;\n return;\n }\n const mn = opts.notMinute;\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return true;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return true;\n return d.getUTCMinutes() !== mn;\n });\n }\n if (\n opts.notMinutes !== undefined &&\n (opts.minute !== undefined || opts.minutes !== undefined || opts.notMinute !== undefined)\n ) {\n console.error(\n `refactor list: --not-minutes is mutually exclusive with --minute, --minutes, and --not-minute; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notMinutes !== undefined) {\n const parts = opts.notMinutes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parts.length === 0) {\n console.error(`refactor list: --not-minutes requires at least one minute value.`);\n process.exitCode = 1;\n return;\n }\n const minutes: number[] = [];\n for (const p of parts) {\n const n = Number(p);\n if (!Number.isFinite(n) || !Number.isInteger(n) || n < 0 || n > 59) {\n console.error(\n `refactor list: --not-minutes entry ${JSON.stringify(p)} must be an integer in [0, 59].`,\n );\n process.exitCode = 1;\n return;\n }\n minutes.push(n);\n }\n const minuteSet = new Set(minutes);\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return true;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return true;\n return !minuteSet.has(d.getUTCMinutes());\n });\n }\n if (opts.second !== undefined) {\n if (\n !Number.isFinite(opts.second) ||\n !Number.isInteger(opts.second) ||\n opts.second < 0 ||\n opts.second > 59\n ) {\n console.error(\n `refactor list: --second ${JSON.stringify(opts.second)} must be an integer in [0, 59].`,\n );\n process.exitCode = 1;\n return;\n }\n const sc = opts.second;\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return false;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return false;\n return d.getUTCSeconds() === sc;\n });\n }\n if (opts.second !== undefined && opts.seconds !== undefined) {\n console.error(`refactor list: --second and --seconds are mutually exclusive; pick one.`);\n process.exitCode = 1;\n return;\n }\n if (opts.seconds !== undefined) {\n const parts = opts.seconds\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parts.length === 0) {\n console.error(`refactor list: --seconds requires at least one second value.`);\n process.exitCode = 1;\n return;\n }\n const seconds: number[] = [];\n for (const p of parts) {\n const n = Number(p);\n if (!Number.isFinite(n) || !Number.isInteger(n) || n < 0 || n > 59) {\n console.error(\n `refactor list: --seconds entry ${JSON.stringify(p)} must be an integer in [0, 59].`,\n );\n process.exitCode = 1;\n return;\n }\n seconds.push(n);\n }\n const secondSet = new Set(seconds);\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return false;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return false;\n return secondSet.has(d.getUTCSeconds());\n });\n }\n if (\n opts.notSecond !== undefined &&\n (opts.second !== undefined || opts.seconds !== undefined)\n ) {\n console.error(\n `refactor list: --not-second is mutually exclusive with --second and --seconds; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notSecond !== undefined) {\n if (\n !Number.isFinite(opts.notSecond) ||\n !Number.isInteger(opts.notSecond) ||\n opts.notSecond < 0 ||\n opts.notSecond > 59\n ) {\n console.error(\n `refactor list: --not-second ${JSON.stringify(opts.notSecond)} must be an integer in [0, 59].`,\n );\n process.exitCode = 1;\n return;\n }\n const sc = opts.notSecond;\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return true;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return true;\n return d.getUTCSeconds() !== sc;\n });\n }\n if (\n opts.notSeconds !== undefined &&\n (opts.second !== undefined || opts.seconds !== undefined || opts.notSecond !== undefined)\n ) {\n console.error(\n `refactor list: --not-seconds is mutually exclusive with --second, --seconds, and --not-second; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notSeconds !== undefined) {\n const parts = opts.notSeconds\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parts.length === 0) {\n console.error(`refactor list: --not-seconds requires at least one second value.`);\n process.exitCode = 1;\n return;\n }\n const seconds: number[] = [];\n for (const p of parts) {\n const n = Number(p);\n if (!Number.isFinite(n) || !Number.isInteger(n) || n < 0 || n > 59) {\n console.error(\n `refactor list: --not-seconds entry ${JSON.stringify(p)} must be an integer in [0, 59].`,\n );\n process.exitCode = 1;\n return;\n }\n seconds.push(n);\n }\n const secondSet = new Set(seconds);\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return true;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return true;\n return !secondSet.has(d.getUTCSeconds());\n });\n }\n if (opts.dayOfMonth !== undefined) {\n if (\n !Number.isFinite(opts.dayOfMonth) ||\n !Number.isInteger(opts.dayOfMonth) ||\n opts.dayOfMonth < 1 ||\n opts.dayOfMonth > 31\n ) {\n console.error(\n `refactor list: --day-of-month ${JSON.stringify(opts.dayOfMonth)} must be an integer in [1, 31].`,\n );\n process.exitCode = 1;\n return;\n }\n const dm = opts.dayOfMonth;\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return false;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return false;\n return d.getUTCDate() === dm;\n });\n }\n if (opts.dayOfMonth !== undefined && opts.daysOfMonth !== undefined) {\n console.error(\n `refactor list: --day-of-month and --days-of-month are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.daysOfMonth !== undefined) {\n const parts = opts.daysOfMonth\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parts.length === 0) {\n console.error(`refactor list: --days-of-month requires at least one day value.`);\n process.exitCode = 1;\n return;\n }\n const days: number[] = [];\n for (const p of parts) {\n const n = Number(p);\n if (!Number.isFinite(n) || !Number.isInteger(n) || n < 1 || n > 31) {\n console.error(\n `refactor list: --days-of-month entry ${JSON.stringify(p)} must be an integer in [1, 31].`,\n );\n process.exitCode = 1;\n return;\n }\n days.push(n);\n }\n const daySet = new Set(days);\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return false;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return false;\n return daySet.has(d.getUTCDate());\n });\n }\n if (\n opts.notDayOfMonth !== undefined &&\n (opts.dayOfMonth !== undefined || opts.daysOfMonth !== undefined)\n ) {\n console.error(\n `refactor list: --not-day-of-month is mutually exclusive with --day-of-month and --days-of-month; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notDayOfMonth !== undefined) {\n if (\n !Number.isFinite(opts.notDayOfMonth) ||\n !Number.isInteger(opts.notDayOfMonth) ||\n opts.notDayOfMonth < 1 ||\n opts.notDayOfMonth > 31\n ) {\n console.error(\n `refactor list: --not-day-of-month ${JSON.stringify(opts.notDayOfMonth)} must be an integer in [1, 31].`,\n );\n process.exitCode = 1;\n return;\n }\n const dm = opts.notDayOfMonth;\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return true;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return true;\n return d.getUTCDate() !== dm;\n });\n }\n if (\n opts.notDaysOfMonth !== undefined &&\n (opts.dayOfMonth !== undefined ||\n opts.daysOfMonth !== undefined ||\n opts.notDayOfMonth !== undefined)\n ) {\n console.error(\n `refactor list: --not-days-of-month is mutually exclusive with --day-of-month, --days-of-month, and --not-day-of-month; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notDaysOfMonth !== undefined) {\n const parts = opts.notDaysOfMonth\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parts.length === 0) {\n console.error(`refactor list: --not-days-of-month requires at least one day value.`);\n process.exitCode = 1;\n return;\n }\n const days: number[] = [];\n for (const p of parts) {\n const n = Number(p);\n if (!Number.isFinite(n) || !Number.isInteger(n) || n < 1 || n > 31) {\n console.error(\n `refactor list: --not-days-of-month entry ${JSON.stringify(p)} must be an integer in [1, 31].`,\n );\n process.exitCode = 1;\n return;\n }\n days.push(n);\n }\n const daySet = new Set(days);\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return true;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return true;\n return !daySet.has(d.getUTCDate());\n });\n }\n if (opts.quarter !== undefined) {\n if (\n !Number.isFinite(opts.quarter) ||\n !Number.isInteger(opts.quarter) ||\n opts.quarter < 1 ||\n opts.quarter > 4\n ) {\n console.error(\n `refactor list: --quarter ${JSON.stringify(opts.quarter)} must be an integer in [1, 4].`,\n );\n process.exitCode = 1;\n return;\n }\n const q = opts.quarter;\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return false;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return false;\n return Math.floor(d.getUTCMonth() / 3) + 1 === q;\n });\n }\n if (opts.quarter !== undefined && opts.quarters !== undefined) {\n console.error(\n `refactor list: --quarter and --quarters are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.quarters !== undefined) {\n const parts = opts.quarters\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parts.length === 0) {\n console.error(`refactor list: --quarters requires at least one quarter value.`);\n process.exitCode = 1;\n return;\n }\n const quarters: number[] = [];\n for (const p of parts) {\n const n = Number(p);\n if (!Number.isFinite(n) || !Number.isInteger(n) || n < 1 || n > 4) {\n console.error(\n `refactor list: --quarters entry ${JSON.stringify(p)} must be an integer in [1, 4].`,\n );\n process.exitCode = 1;\n return;\n }\n quarters.push(n);\n }\n const quarterSet = new Set(quarters);\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return false;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return false;\n return quarterSet.has(Math.floor(d.getUTCMonth() / 3) + 1);\n });\n }\n if (\n opts.notQuarter !== undefined &&\n (opts.quarter !== undefined || opts.quarters !== undefined)\n ) {\n console.error(\n `refactor list: --not-quarter is mutually exclusive with --quarter and --quarters; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notQuarter !== undefined) {\n if (\n !Number.isFinite(opts.notQuarter) ||\n !Number.isInteger(opts.notQuarter) ||\n opts.notQuarter < 1 ||\n opts.notQuarter > 4\n ) {\n console.error(\n `refactor list: --not-quarter ${JSON.stringify(opts.notQuarter)} must be an integer in [1, 4].`,\n );\n process.exitCode = 1;\n return;\n }\n const q = opts.notQuarter;\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return true;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return true;\n return Math.floor(d.getUTCMonth() / 3) + 1 !== q;\n });\n }\n if (\n opts.notQuarters !== undefined &&\n (opts.quarter !== undefined ||\n opts.quarters !== undefined ||\n opts.notQuarter !== undefined)\n ) {\n console.error(\n `refactor list: --not-quarters is mutually exclusive with --quarter, --quarters, and --not-quarter; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notQuarters !== undefined) {\n const parts = opts.notQuarters\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parts.length === 0) {\n console.error(`refactor list: --not-quarters requires at least one quarter value.`);\n process.exitCode = 1;\n return;\n }\n const quarters: number[] = [];\n for (const p of parts) {\n const n = Number(p);\n if (!Number.isFinite(n) || !Number.isInteger(n) || n < 1 || n > 4) {\n console.error(\n `refactor list: --not-quarters entry ${JSON.stringify(p)} must be an integer in [1, 4].`,\n );\n process.exitCode = 1;\n return;\n }\n quarters.push(n);\n }\n const quarterSet = new Set(quarters);\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return true;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return true;\n return !quarterSet.has(Math.floor(d.getUTCMonth() / 3) + 1);\n });\n }\n if (opts.dayOfYear !== undefined) {\n if (\n !Number.isFinite(opts.dayOfYear) ||\n !Number.isInteger(opts.dayOfYear) ||\n opts.dayOfYear < 1 ||\n opts.dayOfYear > 366\n ) {\n console.error(\n `refactor list: --day-of-year ${JSON.stringify(opts.dayOfYear)} must be an integer in [1, 366].`,\n );\n process.exitCode = 1;\n return;\n }\n const dy = opts.dayOfYear;\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return false;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return false;\n const startOfYear = Date.UTC(d.getUTCFullYear(), 0, 1);\n return Math.floor((d.getTime() - startOfYear) / 86400000) + 1 === dy;\n });\n }\n if (opts.dayOfYear !== undefined && opts.daysOfYear !== undefined) {\n console.error(\n `refactor list: --day-of-year and --days-of-year are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.daysOfYear !== undefined) {\n const parts = opts.daysOfYear\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parts.length === 0) {\n console.error(`refactor list: --days-of-year requires at least one day-of-year value.`);\n process.exitCode = 1;\n return;\n }\n const days: number[] = [];\n for (const p of parts) {\n const n = Number(p);\n if (!Number.isFinite(n) || !Number.isInteger(n) || n < 1 || n > 366) {\n console.error(\n `refactor list: --days-of-year entry ${JSON.stringify(p)} must be an integer in [1, 366].`,\n );\n process.exitCode = 1;\n return;\n }\n days.push(n);\n }\n const daySet = new Set(days);\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return false;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return false;\n const startOfYear = Date.UTC(d.getUTCFullYear(), 0, 1);\n return daySet.has(Math.floor((d.getTime() - startOfYear) / 86400000) + 1);\n });\n }\n if (\n opts.notDayOfYear !== undefined &&\n (opts.dayOfYear !== undefined || opts.daysOfYear !== undefined)\n ) {\n console.error(\n `refactor list: --not-day-of-year is mutually exclusive with --day-of-year and --days-of-year; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notDayOfYear !== undefined) {\n if (\n !Number.isFinite(opts.notDayOfYear) ||\n !Number.isInteger(opts.notDayOfYear) ||\n opts.notDayOfYear < 1 ||\n opts.notDayOfYear > 366\n ) {\n console.error(\n `refactor list: --not-day-of-year ${JSON.stringify(opts.notDayOfYear)} must be an integer in [1, 366].`,\n );\n process.exitCode = 1;\n return;\n }\n const dy = opts.notDayOfYear;\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return true;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return true;\n const startOfYear = Date.UTC(d.getUTCFullYear(), 0, 1);\n return Math.floor((d.getTime() - startOfYear) / 86400000) + 1 !== dy;\n });\n }\n if (\n opts.notDaysOfYear !== undefined &&\n (opts.dayOfYear !== undefined ||\n opts.daysOfYear !== undefined ||\n opts.notDayOfYear !== undefined)\n ) {\n console.error(\n `refactor list: --not-days-of-year is mutually exclusive with --day-of-year, --days-of-year, and --not-day-of-year; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notDaysOfYear !== undefined) {\n const parts = opts.notDaysOfYear\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parts.length === 0) {\n console.error(\n `refactor list: --not-days-of-year requires at least one day-of-year value.`,\n );\n process.exitCode = 1;\n return;\n }\n const days: number[] = [];\n for (const p of parts) {\n const n = Number(p);\n if (!Number.isFinite(n) || !Number.isInteger(n) || n < 1 || n > 366) {\n console.error(\n `refactor list: --not-days-of-year entry ${JSON.stringify(p)} must be an integer in [1, 366].`,\n );\n process.exitCode = 1;\n return;\n }\n days.push(n);\n }\n const daySet = new Set(days);\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return true;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return true;\n const startOfYear = Date.UTC(d.getUTCFullYear(), 0, 1);\n return !daySet.has(Math.floor((d.getTime() - startOfYear) / 86400000) + 1);\n });\n }\n if (opts.weekOfYear !== undefined) {\n if (\n !Number.isFinite(opts.weekOfYear) ||\n !Number.isInteger(opts.weekOfYear) ||\n opts.weekOfYear < 1 ||\n opts.weekOfYear > 53\n ) {\n console.error(\n `refactor list: --week-of-year ${JSON.stringify(opts.weekOfYear)} must be an integer in [1, 53].`,\n );\n process.exitCode = 1;\n return;\n }\n const w = opts.weekOfYear;\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return false;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return false;\n const startOfYear = Date.UTC(d.getUTCFullYear(), 0, 1);\n return Math.floor((d.getTime() - startOfYear) / 86400000 / 7) + 1 === w;\n });\n }\n if (opts.weekOfYear !== undefined && opts.weeksOfYear !== undefined) {\n console.error(\n `refactor list: --week-of-year and --weeks-of-year are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.weeksOfYear !== undefined) {\n const parts = opts.weeksOfYear\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parts.length === 0) {\n console.error(\n `refactor list: --weeks-of-year requires at least one week-of-year value.`,\n );\n process.exitCode = 1;\n return;\n }\n const weeks: number[] = [];\n for (const p of parts) {\n const n = Number(p);\n if (!Number.isFinite(n) || !Number.isInteger(n) || n < 1 || n > 53) {\n console.error(\n `refactor list: --weeks-of-year entry ${JSON.stringify(p)} must be an integer in [1, 53].`,\n );\n process.exitCode = 1;\n return;\n }\n weeks.push(n);\n }\n const weekSet = new Set(weeks);\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return false;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return false;\n const startOfYear = Date.UTC(d.getUTCFullYear(), 0, 1);\n return weekSet.has(Math.floor((d.getTime() - startOfYear) / 86400000 / 7) + 1);\n });\n }\n if (\n opts.notWeekOfYear !== undefined &&\n (opts.weekOfYear !== undefined || opts.weeksOfYear !== undefined)\n ) {\n console.error(\n `refactor list: --not-week-of-year is mutually exclusive with --week-of-year and --weeks-of-year; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notWeekOfYear !== undefined) {\n if (\n !Number.isFinite(opts.notWeekOfYear) ||\n !Number.isInteger(opts.notWeekOfYear) ||\n opts.notWeekOfYear < 1 ||\n opts.notWeekOfYear > 53\n ) {\n console.error(\n `refactor list: --not-week-of-year ${JSON.stringify(opts.notWeekOfYear)} must be an integer in [1, 53].`,\n );\n process.exitCode = 1;\n return;\n }\n const w = opts.notWeekOfYear;\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return true;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return true;\n const startOfYear = Date.UTC(d.getUTCFullYear(), 0, 1);\n return Math.floor((d.getTime() - startOfYear) / 86400000 / 7) + 1 !== w;\n });\n }\n if (\n opts.notWeeksOfYear !== undefined &&\n (opts.weekOfYear !== undefined ||\n opts.weeksOfYear !== undefined ||\n opts.notWeekOfYear !== undefined)\n ) {\n console.error(\n `refactor list: --not-weeks-of-year is mutually exclusive with --week-of-year, --weeks-of-year, and --not-week-of-year; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notWeeksOfYear !== undefined) {\n const parts = opts.notWeeksOfYear\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parts.length === 0) {\n console.error(\n `refactor list: --not-weeks-of-year requires at least one week-of-year value.`,\n );\n process.exitCode = 1;\n return;\n }\n const weeks: number[] = [];\n for (const p of parts) {\n const n = Number(p);\n if (!Number.isFinite(n) || !Number.isInteger(n) || n < 1 || n > 53) {\n console.error(\n `refactor list: --not-weeks-of-year entry ${JSON.stringify(p)} must be an integer in [1, 53].`,\n );\n process.exitCode = 1;\n return;\n }\n weeks.push(n);\n }\n const weekSet = new Set(weeks);\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return true;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return true;\n const startOfYear = Date.UTC(d.getUTCFullYear(), 0, 1);\n return !weekSet.has(Math.floor((d.getTime() - startOfYear) / 86400000 / 7) + 1);\n });\n }\n if (opts.weekOfMonth !== undefined) {\n if (\n !Number.isFinite(opts.weekOfMonth) ||\n !Number.isInteger(opts.weekOfMonth) ||\n opts.weekOfMonth < 1 ||\n opts.weekOfMonth > 5\n ) {\n console.error(\n `refactor list: --week-of-month ${JSON.stringify(opts.weekOfMonth)} must be an integer in [1, 5].`,\n );\n process.exitCode = 1;\n return;\n }\n const w = opts.weekOfMonth;\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return false;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return false;\n return Math.floor((d.getUTCDate() - 1) / 7) + 1 === w;\n });\n }\n if (opts.weekOfMonth !== undefined && opts.weeksOfMonth !== undefined) {\n console.error(\n `refactor list: --week-of-month and --weeks-of-month are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.weeksOfMonth !== undefined) {\n const parts = opts.weeksOfMonth\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parts.length === 0) {\n console.error(\n `refactor list: --weeks-of-month requires at least one week-of-month value.`,\n );\n process.exitCode = 1;\n return;\n }\n const weeks: number[] = [];\n for (const p of parts) {\n const n = Number(p);\n if (!Number.isFinite(n) || !Number.isInteger(n) || n < 1 || n > 5) {\n console.error(\n `refactor list: --weeks-of-month entry ${JSON.stringify(p)} must be an integer in [1, 5].`,\n );\n process.exitCode = 1;\n return;\n }\n weeks.push(n);\n }\n const weekSet = new Set(weeks);\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return false;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return false;\n return weekSet.has(Math.floor((d.getUTCDate() - 1) / 7) + 1);\n });\n }\n if (\n opts.notWeekOfMonth !== undefined &&\n (opts.weekOfMonth !== undefined || opts.weeksOfMonth !== undefined)\n ) {\n console.error(\n `refactor list: --not-week-of-month is mutually exclusive with --week-of-month and --weeks-of-month; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notWeekOfMonth !== undefined) {\n if (\n !Number.isFinite(opts.notWeekOfMonth) ||\n !Number.isInteger(opts.notWeekOfMonth) ||\n opts.notWeekOfMonth < 1 ||\n opts.notWeekOfMonth > 5\n ) {\n console.error(\n `refactor list: --not-week-of-month ${JSON.stringify(opts.notWeekOfMonth)} must be an integer in [1, 5].`,\n );\n process.exitCode = 1;\n return;\n }\n const w = opts.notWeekOfMonth;\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return true;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return true;\n return Math.floor((d.getUTCDate() - 1) / 7) + 1 !== w;\n });\n }\n if (\n opts.notWeeksOfMonth !== undefined &&\n (opts.weekOfMonth !== undefined ||\n opts.weeksOfMonth !== undefined ||\n opts.notWeekOfMonth !== undefined)\n ) {\n console.error(\n `refactor list: --not-weeks-of-month is mutually exclusive with --week-of-month, --weeks-of-month, and --not-week-of-month; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notWeeksOfMonth !== undefined) {\n const parts = opts.notWeeksOfMonth\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parts.length === 0) {\n console.error(\n `refactor list: --not-weeks-of-month requires at least one week-of-month value.`,\n );\n process.exitCode = 1;\n return;\n }\n const weeks: number[] = [];\n for (const p of parts) {\n const n = Number(p);\n if (!Number.isFinite(n) || !Number.isInteger(n) || n < 1 || n > 5) {\n console.error(\n `refactor list: --not-weeks-of-month entry ${JSON.stringify(p)} must be an integer in [1, 5].`,\n );\n process.exitCode = 1;\n return;\n }\n weeks.push(n);\n }\n const weekSet = new Set(weeks);\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return true;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return true;\n return !weekSet.has(Math.floor((d.getUTCDate() - 1) / 7) + 1);\n });\n }\n if (opts.millisecond !== undefined) {\n if (\n !Number.isFinite(opts.millisecond) ||\n !Number.isInteger(opts.millisecond) ||\n opts.millisecond < 0 ||\n opts.millisecond > 999\n ) {\n console.error(\n `refactor list: --millisecond ${JSON.stringify(opts.millisecond)} must be an integer in [0, 999].`,\n );\n process.exitCode = 1;\n return;\n }\n const ms = opts.millisecond;\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return false;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return false;\n return d.getUTCMilliseconds() === ms;\n });\n }\n if (opts.millisecond !== undefined && opts.milliseconds !== undefined) {\n console.error(\n `refactor list: --millisecond and --milliseconds are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.milliseconds !== undefined) {\n const parts = opts.milliseconds\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parts.length === 0) {\n console.error(`refactor list: --milliseconds requires at least one millisecond value.`);\n process.exitCode = 1;\n return;\n }\n const ms: number[] = [];\n for (const p of parts) {\n const n = Number(p);\n if (!Number.isFinite(n) || !Number.isInteger(n) || n < 0 || n > 999) {\n console.error(\n `refactor list: --milliseconds entry ${JSON.stringify(p)} must be an integer in [0, 999].`,\n );\n process.exitCode = 1;\n return;\n }\n ms.push(n);\n }\n const msSet = new Set(ms);\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return false;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return false;\n return msSet.has(d.getUTCMilliseconds());\n });\n }\n if (\n opts.notMillisecond !== undefined &&\n (opts.millisecond !== undefined || opts.milliseconds !== undefined)\n ) {\n console.error(\n `refactor list: --not-millisecond is mutually exclusive with --millisecond and --milliseconds; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notMillisecond !== undefined) {\n if (\n !Number.isFinite(opts.notMillisecond) ||\n !Number.isInteger(opts.notMillisecond) ||\n opts.notMillisecond < 0 ||\n opts.notMillisecond > 999\n ) {\n console.error(\n `refactor list: --not-millisecond ${JSON.stringify(opts.notMillisecond)} must be an integer in [0, 999].`,\n );\n process.exitCode = 1;\n return;\n }\n const ms = opts.notMillisecond;\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return true;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return true;\n return d.getUTCMilliseconds() !== ms;\n });\n }\n if (\n opts.notMilliseconds !== undefined &&\n (opts.millisecond !== undefined ||\n opts.milliseconds !== undefined ||\n opts.notMillisecond !== undefined)\n ) {\n console.error(\n `refactor list: --not-milliseconds is mutually exclusive with --millisecond, --milliseconds, and --not-millisecond; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.notMilliseconds !== undefined) {\n const parts = opts.notMilliseconds\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parts.length === 0) {\n console.error(\n `refactor list: --not-milliseconds requires at least one millisecond value.`,\n );\n process.exitCode = 1;\n return;\n }\n const ms: number[] = [];\n for (const p of parts) {\n const n = Number(p);\n if (!Number.isFinite(n) || !Number.isInteger(n) || n < 0 || n > 999) {\n console.error(\n `refactor list: --not-milliseconds entry ${JSON.stringify(p)} must be an integer in [0, 999].`,\n );\n process.exitCode = 1;\n return;\n }\n ms.push(n);\n }\n const msSet = new Set(ms);\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return true;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return true;\n return !msSet.has(d.getUTCMilliseconds());\n });\n }\n if (opts.minuteOfDay !== undefined) {\n if (\n !Number.isFinite(opts.minuteOfDay) ||\n !Number.isInteger(opts.minuteOfDay) ||\n opts.minuteOfDay < 0 ||\n opts.minuteOfDay > 1439\n ) {\n console.error(\n `refactor list: --minute-of-day ${JSON.stringify(opts.minuteOfDay)} must be an integer in [0, 1439].`,\n );\n process.exitCode = 1;\n return;\n }\n const mod = opts.minuteOfDay;\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return false;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return false;\n return d.getUTCHours() * 60 + d.getUTCMinutes() === mod;\n });\n }\n if (opts.minuteOfDay !== undefined && opts.minutesOfDay !== undefined) {\n console.error(\n `refactor list: --minute-of-day and --minutes-of-day are mutually exclusive; pick one.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.minutesOfDay !== undefined) {\n const parts = opts.minutesOfDay\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (parts.length === 0) {\n console.error(\n `refactor list: --minutes-of-day requires at least one minute-of-day value.`,\n );\n process.exitCode = 1;\n return;\n }\n const mods: number[] = [];\n for (const p of parts) {\n const n = Number(p);\n if (!Number.isFinite(n) || !Number.isInteger(n) || n < 0 || n > 1439) {\n console.error(\n `refactor list: --minutes-of-day entry ${JSON.stringify(p)} must be an integer in [0, 1439].`,\n );\n process.exitCode = 1;\n return;\n }\n mods.push(n);\n }\n const modSet = new Set(mods);\n operations = operations.filter((o) => {\n if (typeof o.timestamp !== 'string') return false;\n const d = new Date(o.timestamp);\n if (Number.isNaN(d.getTime())) return false;\n return modSet.has(d.getUTCHours() * 60 + d.getUTCMinutes());\n });\n }\n if (opts.reverse) {\n // Reverse the displayed/JSON order AFTER --last so callers asking\n // for \"most recent 5, newest on top\" get exactly that.\n operations = [...operations].reverse();\n }\n if (opts.count && opts.summary) {\n console.error(`refactor list: --count and --summary are mutually exclusive; pick one.`);\n process.exitCode = 1;\n return;\n }\n if (opts.csv && (opts.json || opts.count || opts.summary)) {\n console.error(\n `refactor list: --csv is mutually exclusive with --json, --count, --summary; pick one output mode.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.count) {\n if (opts.json) {\n process.stdout.write(JSON.stringify({ count: operations.length }) + '\\n');\n } else {\n process.stdout.write(`${operations.length}\\n`);\n }\n return;\n }\n if (opts.summary) {\n const byType: Record<string, number> = {};\n for (const op of operations) {\n byType[op.type] = (byType[op.type] ?? 0) + 1;\n }\n if (opts.json) {\n process.stdout.write(JSON.stringify({ total: operations.length, byType }) + '\\n');\n } else {\n console.log(`Refactor log summary: ${logPath} (${operations.length} op(s) total)`);\n const kinds = Object.keys(byType).sort();\n for (const kind of kinds) {\n console.log(` ${kind}: ${byType[kind]}`);\n }\n }\n return;\n }\n if (opts.csv) {\n // RFC 4180: quote a field if it contains comma, double-quote, CR or LF.\n // Escape any embedded `\"` by doubling them (`\"\"`).\n const csvEscape = (raw: unknown): string => {\n if (raw === undefined || raw === null) return '';\n const s = String(raw);\n if (/[\",\\r\\n]/.test(s)) return `\"${s.replace(/\"/g, '\"\"')}\"`;\n return s;\n };\n const headers = [\n 'id',\n 'timestamp',\n 'type',\n 'database',\n 'schema',\n 'name',\n 'objectType',\n 'note',\n ];\n const lines = [headers.join(',')];\n for (const op of operations) {\n lines.push(\n [\n csvEscape(op.id),\n csvEscape(op.timestamp),\n csvEscape(op.type),\n csvEscape(op.object?.database),\n csvEscape(op.object?.schema),\n csvEscape(op.object?.name),\n csvEscape(op.object?.objectType),\n csvEscape(op.note),\n ].join(','),\n );\n }\n process.stdout.write(lines.join('\\n') + '\\n');\n return;\n }\n if (opts.json) {\n process.stdout.write(JSON.stringify({ ...log, operations }, null, 2) + '\\n');\n return;\n }\n const annotations: string[] = [];\n if (wantKind) annotations.push(`matching type=${wantKind}`);\n if (excludeKind) annotations.push(`excluding type=${excludeKind}`);\n if (wantKindSet !== undefined) annotations.push(`types=${[...wantKindSet].join(',')}`);\n if (excludeKindSet !== undefined)\n annotations.push(`not-types=${[...excludeKindSet].join(',')}`);\n if (sinceMs !== undefined)\n annotations.push(`since=${opts.since ?? `now-${opts.sinceRelative}`}`);\n if (untilMs !== undefined)\n annotations.push(`until=${opts.until ?? `now-${opts.untilRelative}`}`);\n if (opts.id !== undefined) annotations.push(`id=${opts.id}`);\n if (opts.notId !== undefined) annotations.push(`not-id=${opts.notId}`);\n if (opts.ids !== undefined) {\n const parsed = opts.ids\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`ids=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.notIds !== undefined) {\n const parsed = opts.notIds\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`not-ids=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.idPrefix !== undefined) annotations.push(`id-prefix=${opts.idPrefix}`);\n if (opts.notIdPrefix !== undefined) annotations.push(`not-id-prefix=${opts.notIdPrefix}`);\n if (opts.idPrefixes !== undefined) {\n const parsed = opts.idPrefixes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`id-prefixes=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.notIdPrefixes !== undefined) {\n const parsed = opts.notIdPrefixes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`not-id-prefixes=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.idSuffix !== undefined) annotations.push(`id-suffix=${opts.idSuffix}`);\n if (opts.notIdSuffix !== undefined) annotations.push(`not-id-suffix=${opts.notIdSuffix}`);\n if (opts.idSuffixes !== undefined) {\n const parsed = opts.idSuffixes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`id-suffixes=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.notIdSuffixes !== undefined) {\n const parsed = opts.notIdSuffixes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`not-id-suffixes=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.idContains !== undefined) annotations.push(`id-contains=${opts.idContains}`);\n if (opts.notIdContains !== undefined)\n annotations.push(`not-id-contains=${opts.notIdContains}`);\n if (opts.idContainsAny !== undefined) {\n const parsed = opts.idContainsAny\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`id-contains-any=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.notIdContainsAny !== undefined) {\n const parsed = opts.notIdContainsAny\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`not-id-contains-any=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.idContainsAll !== undefined) {\n const parsed = opts.idContainsAll\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`id-contains-all=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.notIdContainsAll !== undefined) {\n const parsed = opts.notIdContainsAll\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`not-id-contains-all=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.idRegex !== undefined)\n annotations.push(`id-regex=${JSON.stringify(opts.idRegex)}`);\n if (opts.notIdRegex !== undefined)\n annotations.push(`not-id-regex=${JSON.stringify(opts.notIdRegex)}`);\n if (opts.noteContains !== undefined)\n annotations.push(`note-contains=${JSON.stringify(opts.noteContains)}`);\n if (opts.notNoteContains !== undefined)\n annotations.push(`not-note-contains=${JSON.stringify(opts.notNoteContains)}`);\n if (opts.noteContainsAny !== undefined) {\n const parsed = opts.noteContainsAny\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`note-contains-any=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.notNoteContainsAny !== undefined) {\n const parsed = opts.notNoteContainsAny\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(\n `not-note-contains-any=${parsed.map((s) => JSON.stringify(s)).join(',')}`,\n );\n }\n if (opts.noteContainsAll !== undefined) {\n const parsed = opts.noteContainsAll\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`note-contains-all=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.notNoteContainsAll !== undefined) {\n const parsed = opts.notNoteContainsAll\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(\n `not-note-contains-all=${parsed.map((s) => JSON.stringify(s)).join(',')}`,\n );\n }\n if (opts.noteRegex !== undefined)\n annotations.push(`note-regex=${JSON.stringify(opts.noteRegex)}`);\n if (opts.notNoteRegex !== undefined)\n annotations.push(`not-note-regex=${JSON.stringify(opts.notNoteRegex)}`);\n if (opts.notePrefix !== undefined)\n annotations.push(`note-prefix=${JSON.stringify(opts.notePrefix)}`);\n if (opts.notNotePrefix !== undefined)\n annotations.push(`not-note-prefix=${JSON.stringify(opts.notNotePrefix)}`);\n if (opts.notePrefixes !== undefined) {\n const parsed = opts.notePrefixes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`note-prefixes=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.notNotePrefixes !== undefined) {\n const parsed = opts.notNotePrefixes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`not-note-prefixes=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.noteSuffix !== undefined)\n annotations.push(`note-suffix=${JSON.stringify(opts.noteSuffix)}`);\n if (opts.notNoteSuffix !== undefined)\n annotations.push(`not-note-suffix=${JSON.stringify(opts.notNoteSuffix)}`);\n if (opts.noteSuffixes !== undefined) {\n const parsed = opts.noteSuffixes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`note-suffixes=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.notNoteSuffixes !== undefined) {\n const parsed = opts.notNoteSuffixes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`not-note-suffixes=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.noteExact !== undefined)\n annotations.push(`note-exact=${JSON.stringify(opts.noteExact)}`);\n if (opts.notes !== undefined) {\n const parsed = opts.notes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`notes=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.notNotes !== undefined) {\n const parsed = opts.notNotes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`not-notes=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.notNoteExact !== undefined)\n annotations.push(`not-note-exact=${JSON.stringify(opts.notNoteExact)}`);\n if (opts.objectType !== undefined)\n annotations.push(`object-type=${opts.objectType.toUpperCase()}`);\n if (opts.objectTypes !== undefined) {\n const parsed = opts.objectTypes\n .split(',')\n .map((s) => s.trim().toUpperCase())\n .filter((s) => s.length > 0);\n annotations.push(`object-types=${parsed.join(',')}`);\n }\n if (opts.notObjectTypes !== undefined) {\n const parsed = opts.notObjectTypes\n .split(',')\n .map((s) => s.trim().toUpperCase())\n .filter((s) => s.length > 0);\n annotations.push(`not-object-types=${parsed.join(',')}`);\n }\n if (opts.notObjectType !== undefined)\n annotations.push(`not-object-type=${opts.notObjectType.toUpperCase()}`);\n if (opts.name !== undefined) annotations.push(`name=${JSON.stringify(opts.name)}`);\n if (opts.notName !== undefined)\n annotations.push(`not-name=${JSON.stringify(opts.notName)}`);\n if (opts.nameContainsAny !== undefined) {\n const parsed = opts.nameContainsAny\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`name-contains-any=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.notNameContainsAny !== undefined) {\n const parsed = opts.notNameContainsAny\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(\n `not-name-contains-any=${parsed.map((s) => JSON.stringify(s)).join(',')}`,\n );\n }\n if (opts.nameContainsAll !== undefined) {\n const parsed = opts.nameContainsAll\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`name-contains-all=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.notNameContainsAll !== undefined) {\n const parsed = opts.notNameContainsAll\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(\n `not-name-contains-all=${parsed.map((s) => JSON.stringify(s)).join(',')}`,\n );\n }\n if (opts.nameRegex !== undefined)\n annotations.push(`name-regex=${JSON.stringify(opts.nameRegex)}`);\n if (opts.notNameRegex !== undefined)\n annotations.push(`not-name-regex=${JSON.stringify(opts.notNameRegex)}`);\n if (opts.namePrefix !== undefined)\n annotations.push(`name-prefix=${JSON.stringify(opts.namePrefix)}`);\n if (opts.notNamePrefix !== undefined)\n annotations.push(`not-name-prefix=${JSON.stringify(opts.notNamePrefix)}`);\n if (opts.namePrefixes !== undefined) {\n const parsed = opts.namePrefixes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`name-prefixes=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.notNamePrefixes !== undefined) {\n const parsed = opts.notNamePrefixes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`not-name-prefixes=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.nameSuffix !== undefined)\n annotations.push(`name-suffix=${JSON.stringify(opts.nameSuffix)}`);\n if (opts.notNameSuffix !== undefined)\n annotations.push(`not-name-suffix=${JSON.stringify(opts.notNameSuffix)}`);\n if (opts.nameSuffixes !== undefined) {\n const parsed = opts.nameSuffixes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`name-suffixes=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.notNameSuffixes !== undefined) {\n const parsed = opts.notNameSuffixes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`not-name-suffixes=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.nameExact !== undefined)\n annotations.push(`name-exact=${JSON.stringify(opts.nameExact)}`);\n if (opts.names !== undefined) {\n const parsed = opts.names\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`names=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.notNames !== undefined) {\n const parsed = opts.notNames\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`not-names=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.notNameExact !== undefined)\n annotations.push(`not-name-exact=${JSON.stringify(opts.notNameExact)}`);\n if (opts.schema !== undefined) annotations.push(`schema=${JSON.stringify(opts.schema)}`);\n if (opts.notSchema !== undefined)\n annotations.push(`not-schema=${JSON.stringify(opts.notSchema)}`);\n if (opts.schemaContainsAny !== undefined) {\n const parsed = opts.schemaContainsAny\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`schema-contains-any=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.notSchemaContainsAny !== undefined) {\n const parsed = opts.notSchemaContainsAny\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(\n `not-schema-contains-any=${parsed.map((s) => JSON.stringify(s)).join(',')}`,\n );\n }\n if (opts.schemaContainsAll !== undefined) {\n const parsed = opts.schemaContainsAll\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`schema-contains-all=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.notSchemaContainsAll !== undefined) {\n const parsed = opts.notSchemaContainsAll\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(\n `not-schema-contains-all=${parsed.map((s) => JSON.stringify(s)).join(',')}`,\n );\n }\n if (opts.schemaRegex !== undefined)\n annotations.push(`schema-regex=${JSON.stringify(opts.schemaRegex)}`);\n if (opts.notSchemaRegex !== undefined)\n annotations.push(`not-schema-regex=${JSON.stringify(opts.notSchemaRegex)}`);\n if (opts.schemaPrefix !== undefined)\n annotations.push(`schema-prefix=${JSON.stringify(opts.schemaPrefix)}`);\n if (opts.notSchemaPrefix !== undefined)\n annotations.push(`not-schema-prefix=${JSON.stringify(opts.notSchemaPrefix)}`);\n if (opts.schemaPrefixes !== undefined) {\n const parsed = opts.schemaPrefixes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`schema-prefixes=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.notSchemaPrefixes !== undefined) {\n const parsed = opts.notSchemaPrefixes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`not-schema-prefixes=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.schemaSuffix !== undefined)\n annotations.push(`schema-suffix=${JSON.stringify(opts.schemaSuffix)}`);\n if (opts.notSchemaSuffix !== undefined)\n annotations.push(`not-schema-suffix=${JSON.stringify(opts.notSchemaSuffix)}`);\n if (opts.schemaSuffixes !== undefined) {\n const parsed = opts.schemaSuffixes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`schema-suffixes=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.notSchemaSuffixes !== undefined) {\n const parsed = opts.notSchemaSuffixes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`not-schema-suffixes=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.schemaExact !== undefined)\n annotations.push(`schema-exact=${JSON.stringify(opts.schemaExact)}`);\n if (opts.schemas !== undefined) {\n const parsed = opts.schemas\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`schemas=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.notSchemas !== undefined) {\n const parsed = opts.notSchemas\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`not-schemas=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.notSchemaExact !== undefined)\n annotations.push(`not-schema-exact=${JSON.stringify(opts.notSchemaExact)}`);\n if (opts.database !== undefined)\n annotations.push(`database=${JSON.stringify(opts.database)}`);\n if (opts.notDatabase !== undefined)\n annotations.push(`not-database=${JSON.stringify(opts.notDatabase)}`);\n if (opts.databaseContainsAny !== undefined) {\n const parsed = opts.databaseContainsAny\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(\n `database-contains-any=${parsed.map((s) => JSON.stringify(s)).join(',')}`,\n );\n }\n if (opts.notDatabaseContainsAny !== undefined) {\n const parsed = opts.notDatabaseContainsAny\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(\n `not-database-contains-any=${parsed.map((s) => JSON.stringify(s)).join(',')}`,\n );\n }\n if (opts.databaseContainsAll !== undefined) {\n const parsed = opts.databaseContainsAll\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(\n `database-contains-all=${parsed.map((s) => JSON.stringify(s)).join(',')}`,\n );\n }\n if (opts.notDatabaseContainsAll !== undefined) {\n const parsed = opts.notDatabaseContainsAll\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(\n `not-database-contains-all=${parsed.map((s) => JSON.stringify(s)).join(',')}`,\n );\n }\n if (opts.databaseRegex !== undefined)\n annotations.push(`database-regex=${JSON.stringify(opts.databaseRegex)}`);\n if (opts.notDatabaseRegex !== undefined)\n annotations.push(`not-database-regex=${JSON.stringify(opts.notDatabaseRegex)}`);\n if (opts.databasePrefix !== undefined)\n annotations.push(`database-prefix=${JSON.stringify(opts.databasePrefix)}`);\n if (opts.notDatabasePrefix !== undefined)\n annotations.push(`not-database-prefix=${JSON.stringify(opts.notDatabasePrefix)}`);\n if (opts.databasePrefixes !== undefined) {\n const parsed = opts.databasePrefixes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`database-prefixes=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.notDatabasePrefixes !== undefined) {\n const parsed = opts.notDatabasePrefixes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(\n `not-database-prefixes=${parsed.map((s) => JSON.stringify(s)).join(',')}`,\n );\n }\n if (opts.databaseSuffix !== undefined)\n annotations.push(`database-suffix=${JSON.stringify(opts.databaseSuffix)}`);\n if (opts.notDatabaseSuffix !== undefined)\n annotations.push(`not-database-suffix=${JSON.stringify(opts.notDatabaseSuffix)}`);\n if (opts.databaseSuffixes !== undefined) {\n const parsed = opts.databaseSuffixes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`database-suffixes=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.notDatabaseSuffixes !== undefined) {\n const parsed = opts.notDatabaseSuffixes\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(\n `not-database-suffixes=${parsed.map((s) => JSON.stringify(s)).join(',')}`,\n );\n }\n if (opts.databaseExact !== undefined)\n annotations.push(`database-exact=${JSON.stringify(opts.databaseExact)}`);\n if (opts.databases !== undefined) {\n const parsed = opts.databases\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`databases=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.notDatabases !== undefined) {\n const parsed = opts.notDatabases\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n annotations.push(`not-databases=${parsed.map((s) => JSON.stringify(s)).join(',')}`);\n }\n if (opts.notDatabaseExact !== undefined)\n annotations.push(`not-database-exact=${JSON.stringify(opts.notDatabaseExact)}`);\n if (opts.nameMinLength !== undefined)\n annotations.push(`name-min-length=${opts.nameMinLength}`);\n if (opts.nameMaxLength !== undefined)\n annotations.push(`name-max-length=${opts.nameMaxLength}`);\n if (opts.schemaMinLength !== undefined)\n annotations.push(`schema-min-length=${opts.schemaMinLength}`);\n if (opts.schemaMaxLength !== undefined)\n annotations.push(`schema-max-length=${opts.schemaMaxLength}`);\n if (opts.databaseMinLength !== undefined)\n annotations.push(`database-min-length=${opts.databaseMinLength}`);\n if (opts.databaseMaxLength !== undefined)\n annotations.push(`database-max-length=${opts.databaseMaxLength}`);\n if (opts.noteMinLength !== undefined)\n annotations.push(`note-min-length=${opts.noteMinLength}`);\n if (opts.noteMaxLength !== undefined)\n annotations.push(`note-max-length=${opts.noteMaxLength}`);\n if (opts.idMinLength !== undefined) annotations.push(`id-min-length=${opts.idMinLength}`);\n if (opts.idMaxLength !== undefined) annotations.push(`id-max-length=${opts.idMaxLength}`);\n if (opts.year !== undefined) annotations.push(`year=${opts.year}`);\n if (opts.years !== undefined) annotations.push(`years=${opts.years}`);\n if (opts.notYear !== undefined) annotations.push(`not-year=${opts.notYear}`);\n if (opts.notYears !== undefined) annotations.push(`not-years=${opts.notYears}`);\n if (opts.month !== undefined) annotations.push(`month=${opts.month}`);\n if (opts.months !== undefined) annotations.push(`months=${opts.months}`);\n if (opts.notMonth !== undefined) annotations.push(`not-month=${opts.notMonth}`);\n if (opts.notMonths !== undefined) annotations.push(`not-months=${opts.notMonths}`);\n if (opts.dayOfWeek !== undefined) annotations.push(`day-of-week=${opts.dayOfWeek}`);\n if (opts.daysOfWeek !== undefined) annotations.push(`days-of-week=${opts.daysOfWeek}`);\n if (opts.notDayOfWeek !== undefined)\n annotations.push(`not-day-of-week=${opts.notDayOfWeek}`);\n if (opts.notDaysOfWeek !== undefined)\n annotations.push(`not-days-of-week=${opts.notDaysOfWeek}`);\n if (opts.hour !== undefined) annotations.push(`hour=${opts.hour}`);\n if (opts.hours !== undefined) annotations.push(`hours=${opts.hours}`);\n if (opts.notHour !== undefined) annotations.push(`not-hour=${opts.notHour}`);\n if (opts.notHours !== undefined) annotations.push(`not-hours=${opts.notHours}`);\n if (opts.minute !== undefined) annotations.push(`minute=${opts.minute}`);\n if (opts.minutes !== undefined) annotations.push(`minutes=${opts.minutes}`);\n if (opts.notMinute !== undefined) annotations.push(`not-minute=${opts.notMinute}`);\n if (opts.notMinutes !== undefined) annotations.push(`not-minutes=${opts.notMinutes}`);\n if (opts.second !== undefined) annotations.push(`second=${opts.second}`);\n if (opts.seconds !== undefined) annotations.push(`seconds=${opts.seconds}`);\n if (opts.notSecond !== undefined) annotations.push(`not-second=${opts.notSecond}`);\n if (opts.notSeconds !== undefined) annotations.push(`not-seconds=${opts.notSeconds}`);\n if (opts.dayOfMonth !== undefined) annotations.push(`day-of-month=${opts.dayOfMonth}`);\n if (opts.daysOfMonth !== undefined) annotations.push(`days-of-month=${opts.daysOfMonth}`);\n if (opts.notDayOfMonth !== undefined)\n annotations.push(`not-day-of-month=${opts.notDayOfMonth}`);\n if (opts.notDaysOfMonth !== undefined)\n annotations.push(`not-days-of-month=${opts.notDaysOfMonth}`);\n if (opts.quarter !== undefined) annotations.push(`quarter=${opts.quarter}`);\n if (opts.quarters !== undefined) annotations.push(`quarters=${opts.quarters}`);\n if (opts.notQuarter !== undefined) annotations.push(`not-quarter=${opts.notQuarter}`);\n if (opts.notQuarters !== undefined) annotations.push(`not-quarters=${opts.notQuarters}`);\n if (opts.dayOfYear !== undefined) annotations.push(`day-of-year=${opts.dayOfYear}`);\n if (opts.daysOfYear !== undefined) annotations.push(`days-of-year=${opts.daysOfYear}`);\n if (opts.notDayOfYear !== undefined)\n annotations.push(`not-day-of-year=${opts.notDayOfYear}`);\n if (opts.notDaysOfYear !== undefined)\n annotations.push(`not-days-of-year=${opts.notDaysOfYear}`);\n if (opts.weekOfYear !== undefined) annotations.push(`week-of-year=${opts.weekOfYear}`);\n if (opts.weeksOfYear !== undefined) annotations.push(`weeks-of-year=${opts.weeksOfYear}`);\n if (opts.notWeekOfYear !== undefined)\n annotations.push(`not-week-of-year=${opts.notWeekOfYear}`);\n if (opts.notWeeksOfYear !== undefined)\n annotations.push(`not-weeks-of-year=${opts.notWeeksOfYear}`);\n if (opts.weekOfMonth !== undefined) annotations.push(`week-of-month=${opts.weekOfMonth}`);\n if (opts.weeksOfMonth !== undefined)\n annotations.push(`weeks-of-month=${opts.weeksOfMonth}`);\n if (opts.notWeekOfMonth !== undefined)\n annotations.push(`not-week-of-month=${opts.notWeekOfMonth}`);\n if (opts.notWeeksOfMonth !== undefined)\n annotations.push(`not-weeks-of-month=${opts.notWeeksOfMonth}`);\n if (opts.millisecond !== undefined) annotations.push(`millisecond=${opts.millisecond}`);\n if (opts.milliseconds !== undefined) annotations.push(`milliseconds=${opts.milliseconds}`);\n if (opts.notMillisecond !== undefined)\n annotations.push(`not-millisecond=${opts.notMillisecond}`);\n if (opts.notMilliseconds !== undefined)\n annotations.push(`not-milliseconds=${opts.notMilliseconds}`);\n if (opts.minuteOfDay !== undefined) annotations.push(`minute-of-day=${opts.minuteOfDay}`);\n if (opts.minutesOfDay !== undefined)\n annotations.push(`minutes-of-day=${opts.minutesOfDay}`);\n if (opts.hasDatabase) annotations.push(`has-database=true`);\n if (opts.missingDatabase) annotations.push(`missing-database=true`);\n if (opts.hasSchema) annotations.push(`has-schema=true`);\n if (opts.missingSchema) annotations.push(`missing-schema=true`);\n if (opts.hasNote) annotations.push(`has-note=true`);\n if (opts.missingNote) annotations.push(`missing-note=true`);\n if (opts.last !== undefined) annotations.push(`last=${opts.last}`);\n if (opts.first !== undefined) annotations.push(`first=${opts.first}`);\n if (opts.reverse) annotations.push(`reverse=true`);\n if (!opts.bare) {\n console.log(\n `Refactor log: ${logPath} (${operations.length} op(s)${\n annotations.length > 0 ? `, ${annotations.join(', ')}` : ''\n })`,\n );\n }\n for (const op of operations) {\n console.log(` [${op.timestamp}] ${op.type} ${describe(op)} id=${op.id}`);\n if (op.note) console.log(` note: ${op.note}`);\n }\n },\n );\n\n cmd\n .command('rename-object')\n .description(\n 'Rewrite every reference to <from> with <to> across one or more SQL files. ' +\n 'Uses the shipped planRenameObject + applyRenamePlan substrate; default ' +\n 'prints a per-file occurrence summary to stdout, --apply writes the files.',\n )\n .argument('<files...>', 'SQL files to scan + rewrite')\n .requiredOption('--from <fqn>', 'Old fully-qualified name (e.g. cat.sch.old_table)')\n .requiredOption('--to <fqn>', 'New fully-qualified name (e.g. cat.sch.new_table)')\n .option(\n '--rewrite-bare',\n 'Also rewrite bare unqualified references to the name (dangerous — opt-in)',\n false,\n )\n .option('--apply', 'Write the rewritten SQL back to each file', false)\n .option(\n '--preview-diff',\n 'Emit a Markdown unified-diff preview instead of an occurrence summary (REF.5)',\n false,\n )\n .option('--json', 'Emit machine-readable JSON describing the plan', false)\n .option(\n '--log <path>',\n `Also append a RENAME_OBJECT op to <path> (default: ${DEFAULT_LOG}) so compare emits ALTER … RENAME`,\n )\n .option(\n '--object-type <type>',\n 'Databricks object type for the recorded op (TABLE, VIEW, …). Required with --log',\n )\n .action(\n async (\n files: string[],\n opts: {\n from: string;\n to: string;\n rewriteBare?: boolean;\n apply?: boolean;\n previewDiff?: boolean;\n json?: boolean;\n log?: string;\n objectType?: string;\n },\n ) => {\n if (!files || files.length === 0) {\n console.error('rename-object: at least one <file> argument is required');\n process.exitCode = 1;\n return;\n }\n if (opts.log !== undefined && !opts.objectType) {\n console.error('rename-object: --log requires --object-type <type>');\n process.exitCode = 1;\n return;\n }\n const sources: refactoring.RenameSource[] = [];\n for (const f of files) {\n const abs = path.resolve(f);\n const content = await fs.readFile(abs, 'utf8');\n sources.push({ path: abs, content });\n }\n let plan: refactoring.RenameObjectPlan;\n try {\n plan = planRenameObject(sources, opts.from, opts.to, {\n rewriteBareName: !!opts.rewriteBare,\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n if (opts.json) {\n process.stdout.write(\n JSON.stringify({ ok: false, errorCode: 'PLAN_FAILED', reason: message }) + '\\n',\n );\n } else {\n console.error(`rename-object: ${message}`);\n }\n process.exitCode = 2;\n return;\n }\n\n const blockingConflicts = plan.conflicts.filter(\n (c) => c.kind === 'TARGET_NAME_ALREADY_DEFINED' || c.kind === 'AMBIGUOUS_BARE_NAME',\n );\n const planJsonPayload = {\n ok: blockingConflicts.length === 0,\n from: plan.from.raw,\n to: plan.to.raw,\n totalOccurrences: plan.totalOccurrences,\n fileCount: plan.changes.length,\n changes: plan.changes.map((c) => ({\n path: c.path,\n occurrences: c.occurrences.length,\n })),\n conflicts: plan.conflicts.map((c) => ({\n path: c.path,\n kind: c.kind,\n message: c.message,\n })),\n applied: false as boolean,\n };\n\n if (plan.totalOccurrences === 0) {\n if (opts.json) {\n process.stdout.write(JSON.stringify(planJsonPayload) + '\\n');\n } else {\n console.log(\n `rename-object: no occurrences of '${plan.from.raw}' found in ${sources.length} file(s).`,\n );\n }\n return;\n }\n\n if (blockingConflicts.length > 0) {\n if (opts.json) {\n process.stdout.write(JSON.stringify(planJsonPayload) + '\\n');\n } else {\n console.error(\n `rename-object refused: ${blockingConflicts.length} blocking conflict(s).`,\n );\n for (const c of blockingConflicts) {\n console.error(` ${c.kind} (${c.path || '<global>'}): ${c.message}`);\n }\n }\n process.exitCode = 2;\n return;\n }\n\n if (opts.apply) {\n const rewritten = applyRenamePlan(sources, plan);\n for (const [filePath, content] of rewritten) {\n await fs.writeFile(filePath, content, 'utf8');\n }\n planJsonPayload.applied = true;\n }\n\n let recordedLogPath: string | undefined;\n if (opts.log !== undefined && opts.objectType) {\n const logPath = path.resolve(opts.log === '' ? DEFAULT_LOG : opts.log);\n const log = await ensureLogExists(logPath);\n // DDT's ParsedFqn names the top container `catalog`; the\n // RefactorOperation shape (cross-platform parity) calls the\n // same field `database`, so we map catalog → database here.\n const topContainer = plan.from.catalog;\n const op = {\n type: 'RENAME_OBJECT' as const,\n object: {\n ...(topContainer ? { database: topContainer } : {}),\n ...(plan.from.schema ? { schema: plan.from.schema } : {}),\n name: plan.from.name,\n objectType: opts.objectType as never,\n },\n details: { oldName: plan.from.name, newName: plan.to.name },\n };\n const updated = appendOperation(log, op);\n await fs.mkdir(path.dirname(logPath), { recursive: true });\n await saveRefactorLog(logPath, updated);\n recordedLogPath = logPath;\n }\n\n if (opts.json) {\n if (recordedLogPath !== undefined) {\n (planJsonPayload as Record<string, unknown>)['recordedLogPath'] = recordedLogPath;\n }\n process.stdout.write(JSON.stringify(planJsonPayload) + '\\n');\n return;\n }\n if (opts.previewDiff) {\n const diff = buildRefactorDiff(sources, plan, `Rename ${plan.from.raw} → ${plan.to.raw}`);\n const md = renderRefactorDiffMarkdown(diff);\n process.stdout.write(md);\n if (!md.endsWith('\\n')) process.stdout.write('\\n');\n return;\n }\n const verb = opts.apply ? 'Rewrote' : 'Would rewrite';\n console.log(\n `${verb} ${plan.totalOccurrences} occurrence(s) of '${plan.from.raw}' → '${plan.to.raw}' across ${plan.changes.length} file(s):`,\n );\n for (const change of plan.changes) {\n console.log(` ${change.path} — ${change.occurrences.length} occurrence(s)`);\n }\n if (recordedLogPath !== undefined) {\n console.log(`Recorded RENAME_OBJECT op in ${recordedLogPath}.`);\n }\n if (!opts.apply) {\n console.log('Re-run with --apply to write the changes.');\n }\n },\n );\n\n cmd\n .command('move-object')\n .description(\n 'Move an object across catalogs / schemas, rewriting every reference ' +\n 'across one or more SQL files. Pure text transform on top of planMoveObject + ' +\n 'planRenameObject + applyRenamePlan. Default prints summary, --apply writes files.',\n )\n .argument('<files...>', 'SQL files to scan + rewrite')\n .requiredOption('--from <fqn>', 'Source 3-part FQN (catalog.schema.name)')\n .requiredOption(\n '--to <container>',\n 'Destination container — 1-part (newcat) or 2-part (newcat.newschema)',\n )\n .option(\n '--rewrite-bare',\n 'Also rewrite bare unqualified references (dangerous — opt-in)',\n false,\n )\n .option('--apply', 'Write the rewritten SQL back to each file', false)\n .option(\n '--preview-diff',\n 'Emit a Markdown unified-diff preview instead of an occurrence summary (REF.5)',\n false,\n )\n .option('--json', 'Emit machine-readable JSON describing the plan', false)\n .option(\n '--log <path>',\n `Also append a MOVE_OBJECT op to <path> (default: ${DEFAULT_LOG}) so compare emits ALTER … RENAME`,\n )\n .option(\n '--object-type <type>',\n 'Databricks object type for the recorded op (TABLE, VIEW, …). Required with --log',\n )\n .action(\n async (\n files: string[],\n opts: {\n from: string;\n to: string;\n rewriteBare?: boolean;\n apply?: boolean;\n previewDiff?: boolean;\n json?: boolean;\n log?: string;\n objectType?: string;\n },\n ) => {\n if (!files || files.length === 0) {\n console.error('move-object: at least one <file> argument is required');\n process.exitCode = 1;\n return;\n }\n if (opts.log !== undefined && !opts.objectType) {\n console.error('move-object: --log requires --object-type <type>');\n process.exitCode = 1;\n return;\n }\n const sources: refactoring.RenameSource[] = [];\n for (const f of files) {\n const abs = path.resolve(f);\n const content = await fs.readFile(abs, 'utf8');\n sources.push({ path: abs, content });\n }\n let result: refactoring.MoveObjectPlanResult;\n try {\n result = planMoveObject({\n sources,\n fromFqn: opts.from,\n toContainer: opts.to,\n options: { rewriteBareName: !!opts.rewriteBare },\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n if (opts.json) {\n process.stdout.write(\n JSON.stringify({ ok: false, errorCode: 'PLAN_FAILED', reason: message }) + '\\n',\n );\n } else {\n console.error(`move-object: ${message}`);\n }\n process.exitCode = 2;\n return;\n }\n\n if (!result.ok) {\n if (opts.json) {\n process.stdout.write(\n JSON.stringify({\n ok: false,\n errorCode: result.error.errorCode,\n message: result.error.message,\n }) + '\\n',\n );\n } else {\n console.error(\n `move-object refused: ${result.error.errorCode} — ${result.error.message}`,\n );\n }\n process.exitCode = 2;\n return;\n }\n\n const { plan } = result;\n const blockingConflicts = plan.conflicts.filter(\n (c) => c.kind === 'TARGET_NAME_ALREADY_DEFINED' || c.kind === 'AMBIGUOUS_BARE_NAME',\n );\n const planJsonPayload = {\n ok: blockingConflicts.length === 0,\n kind: plan.kind,\n from: plan.from.raw,\n toFqn: plan.toFqn,\n totalOccurrences: plan.totalOccurrences,\n fileCount: plan.changes.length,\n changes: plan.changes.map((c) => ({\n path: c.path,\n occurrences: c.occurrences.length,\n })),\n conflicts: plan.conflicts.map((c) => ({\n path: c.path,\n kind: c.kind,\n message: c.message,\n })),\n applied: false as boolean,\n };\n\n if (plan.totalOccurrences === 0) {\n if (opts.json) {\n process.stdout.write(JSON.stringify(planJsonPayload) + '\\n');\n } else {\n console.log(\n `move-object: no occurrences of '${plan.from.raw}' found in ${sources.length} file(s).`,\n );\n }\n return;\n }\n\n if (blockingConflicts.length > 0) {\n if (opts.json) {\n process.stdout.write(JSON.stringify(planJsonPayload) + '\\n');\n } else {\n console.error(`move-object refused: ${blockingConflicts.length} blocking conflict(s).`);\n for (const c of blockingConflicts) {\n console.error(` ${c.kind} (${c.path || '<global>'}): ${c.message}`);\n }\n }\n process.exitCode = 2;\n return;\n }\n\n if (opts.apply) {\n const rewritten = applyRenamePlan(sources, plan);\n for (const [filePath, content] of rewritten) {\n await fs.writeFile(filePath, content, 'utf8');\n }\n planJsonPayload.applied = true;\n }\n\n let recordedLogPath: string | undefined;\n if (opts.log !== undefined && opts.objectType) {\n const logPath = path.resolve(opts.log === '' ? DEFAULT_LOG : opts.log);\n const log = await ensureLogExists(logPath);\n // DDT's ParsedFqn names the top container `catalog`; the\n // RefactorOperation shape (cross-platform parity) calls the\n // same field `database`, so we map catalog → database here.\n const fromTop = plan.from.catalog;\n const toParsed = splitFqn(plan.toFqn);\n const op = {\n type: 'MOVE_OBJECT' as const,\n object: {\n ...(fromTop ? { database: fromTop } : {}),\n ...(plan.from.schema ? { schema: plan.from.schema } : {}),\n name: plan.from.name,\n objectType: opts.objectType as never,\n },\n details: {\n oldFqn: {\n ...(fromTop ? { database: fromTop } : {}),\n ...(plan.from.schema ? { schema: plan.from.schema } : {}),\n name: plan.from.name,\n },\n newFqn: toParsed,\n },\n };\n const updated = appendOperation(log, op);\n await fs.mkdir(path.dirname(logPath), { recursive: true });\n await saveRefactorLog(logPath, updated);\n recordedLogPath = logPath;\n }\n\n if (opts.json) {\n if (recordedLogPath !== undefined) {\n (planJsonPayload as Record<string, unknown>)['recordedLogPath'] = recordedLogPath;\n }\n process.stdout.write(JSON.stringify(planJsonPayload) + '\\n');\n return;\n }\n if (opts.previewDiff) {\n const diff = buildRefactorDiff(\n sources,\n plan,\n `Move ${plan.from.raw} → ${plan.toFqn} (${plan.kind})`,\n );\n const md = renderRefactorDiffMarkdown(diff);\n process.stdout.write(md);\n if (!md.endsWith('\\n')) process.stdout.write('\\n');\n return;\n }\n const verb = opts.apply ? 'Rewrote' : 'Would rewrite';\n console.log(\n `${verb} ${plan.totalOccurrences} occurrence(s) of '${plan.from.raw}' → '${plan.toFqn}' (${plan.kind}) across ${plan.changes.length} file(s):`,\n );\n for (const change of plan.changes) {\n console.log(` ${change.path} — ${change.occurrences.length} occurrence(s)`);\n }\n if (recordedLogPath !== undefined) {\n console.log(`Recorded MOVE_OBJECT op in ${recordedLogPath}.`);\n }\n if (!opts.apply) {\n console.log('Re-run with --apply to write the changes.');\n }\n },\n );\n\n cmd\n .command('extract-cte')\n .description(\n 'Extract a SQL subquery (selected by byte range) into a CTE. ' +\n 'Pure text transform — prints rewritten SQL to stdout unless --apply.',\n )\n .argument('<file>', 'SQL file to rewrite')\n .requiredOption('--select-range <range>', 'Byte range \"<start>-<end>\" (0-based, end exclusive)')\n .option('--cte-name <name>', 'Identifier for the new CTE (default: cte_extracted)')\n .option('--apply', 'Write the rewritten SQL back to <file> instead of stdout', false)\n .option('--json', 'Emit machine-readable JSON describing the rewrite', false)\n .action(\n async (\n file: string,\n opts: { selectRange: string; cteName?: string; apply?: boolean; json?: boolean },\n ) => {\n const range = parseSelectRange(opts.selectRange);\n if (range === null) {\n if (opts.json) {\n process.stdout.write(\n JSON.stringify({\n ok: false,\n errorCode: 'INVALID_SELECT_RANGE',\n reason: `--select-range must look like \"<start>-<end>\" with integer offsets; got ${JSON.stringify(opts.selectRange)}`,\n }) + '\\n',\n );\n } else {\n console.error(\n `Invalid --select-range; expected \"<start>-<end>\" (got ${JSON.stringify(opts.selectRange)}).`,\n );\n }\n process.exitCode = 1;\n return;\n }\n const filePath = path.resolve(file);\n const sql = await fs.readFile(filePath, 'utf8');\n const result: refactoring.ExtractCteResult = extractCte({\n sql,\n startOffset: range.start,\n endOffset: range.end,\n ...(opts.cteName ? { cteName: opts.cteName } : {}),\n });\n\n if (!result.ok || !result.occurrence) {\n const payload = {\n ok: false,\n errorCode: result.errorCode ?? 'UNKNOWN',\n reason: result.reason ?? 'extractCte refused without a reason',\n };\n if (opts.json) {\n process.stdout.write(JSON.stringify(payload) + '\\n');\n } else {\n console.error(`extract-cte refused: ${payload.errorCode} — ${payload.reason}`);\n }\n process.exitCode = 2;\n return;\n }\n\n const { cteName, subqueryText, rewrittenSql, hasExistingWith } = result.occurrence;\n if (opts.apply) {\n await fs.writeFile(filePath, rewrittenSql, 'utf8');\n }\n if (opts.json) {\n process.stdout.write(\n JSON.stringify({\n ok: true,\n cteName,\n subqueryText,\n rewrittenSql,\n hasExistingWith,\n applied: !!opts.apply,\n filePath,\n }) + '\\n',\n );\n return;\n }\n if (opts.apply) {\n console.log(\n `Wrote ${filePath} (CTE ${cteName}${hasExistingWith ? ', appended to existing WITH' : ', new WITH clause'}).`,\n );\n } else {\n process.stdout.write(rewrittenSql);\n if (!rewrittenSql.endsWith('\\n')) process.stdout.write('\\n');\n }\n },\n );\n\n cmd\n .command('remove')\n .description('Remove a refactor op from the log by its id.')\n .requiredOption('--id <uuid>', 'Operation id (from `refactor list`)')\n .option('--log <path>', `Path to refactor.json (default: ${DEFAULT_LOG})`)\n .action(async (opts: { id: string; log?: string }) => {\n const logPath = path.resolve(opts.log ?? DEFAULT_LOG);\n const log = await ensureLogExists(logPath);\n const before = log.operations.length;\n const remaining = log.operations.filter((o) => o.id !== opts.id);\n if (remaining.length === before) {\n console.error(`No operation with id ${opts.id} in ${logPath}`);\n process.exitCode = 1;\n return;\n }\n await saveRefactorLog(logPath, { ...log, operations: remaining });\n console.log(`Removed ${before - remaining.length} op(s) from ${logPath}`);\n });\n\n return cmd;\n}\n\nconst VALID_OP_KINDS = [\n 'RENAME_OBJECT',\n 'RENAME_COLUMN',\n 'MOVE_OBJECT',\n 'CHANGE_COLUMN_TYPE',\n 'DROP_COLUMN',\n 'ADD_CONSTRAINT',\n] as const;\n\nfunction parseSelectRange(raw: string): { start: number; end: number } | null {\n if (typeof raw !== 'string') return null;\n const match = /^(-?\\d+)\\s*-\\s*(-?\\d+)$/.exec(raw.trim());\n if (!match) return null;\n const start = Number.parseInt(match[1]!, 10);\n const end = Number.parseInt(match[2]!, 10);\n if (!Number.isInteger(start) || !Number.isInteger(end)) return null;\n return { start, end };\n}\n\nfunction describe(op: refactoring.RefactorOperation): string {\n switch (op.type) {\n case 'RENAME_OBJECT':\n return `${op.object.objectType} ${fqnString(op.object)} → ${op.details.newName}`;\n case 'RENAME_COLUMN':\n return `${fqnString(op.object)}.${op.details.oldName} → ${op.details.newName}`;\n case 'MOVE_OBJECT':\n return `${fqnString(op.object)} → ${[\n op.details.newFqn.database,\n op.details.newFqn.schema,\n op.details.newFqn.name,\n ]\n .filter(Boolean)\n .join('.')}`;\n case 'CHANGE_COLUMN_TYPE':\n return `${fqnString(op.object)}.${op.details.column} ${op.details.oldType} → ${op.details.newType}`;\n case 'DROP_COLUMN':\n return `${fqnString(op.object)}.${op.details.column} (drop)`;\n case 'ADD_CONSTRAINT': {\n const kind = op.details.constraintKind.toLowerCase().replace(/_/g, ' ');\n const cols = op.details.columns.join(', ');\n const src = op.details.fromSuggester ? ' [suggested]' : '';\n return `${fqnString(op.object)}: ADD ${kind} (${cols})${src}`;\n }\n }\n}\n\nfunction fqnString(o: { database?: string; schema?: string; name: string }): string {\n return [o.database, o.schema, o.name].filter(Boolean).join('.');\n}\n","import { promises as fs } from 'node:fs';\nimport { homedir } from 'node:os';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { license as licenseNs } from '@ddt-tools/core';\n\n/**\n * `ddt license` — manage the local license-key file. Open-core, offline,\n * warn-mode (this revision never blocks; missing Pro license only prints\n * a warning when running Pro features).\n *\n * Subcommands:\n * show Print the loaded license payload + verification status.\n * set Install a JWT into ~/.ddt/license.jwt.\n * clear Remove the license file (returns to free tier).\n */\nexport function licenseCommand(): Command {\n const cmd = new Command('license').description(\n 'Manage the DDT license key (open-core, offline, warn-mode in v0.3).',\n );\n\n cmd\n .command('show')\n .description('Show the currently loaded license.')\n .action(async () => {\n const lic = await licenseNs.loadLicense();\n console.log(licenseNs.describeLicense(lic));\n });\n\n cmd\n .command('set')\n .description('Install a license JWT to ~/.ddt/license.jwt.')\n .requiredOption('--jwt <token>', 'The full JWT string (3 dot-separated base64url parts).')\n .action(async (opts: { jwt: string }) => {\n const target = process.env['DDT_LICENSE_PATH'] ?? path.join(homedir(), '.ddt', 'license.jwt');\n await fs.mkdir(path.dirname(target), { recursive: true });\n await fs.writeFile(target, opts.jwt.trim() + '\\n', 'utf8');\n const lic = await licenseNs.loadLicense();\n console.log(`Wrote ${target}.`);\n console.log(licenseNs.describeLicense(lic));\n });\n\n cmd\n .command('clear')\n .description('Remove the local license file (returns to free tier).')\n .action(async () => {\n const target = process.env['DDT_LICENSE_PATH'] ?? path.join(homedir(), '.ddt', 'license.jwt');\n try {\n await fs.unlink(target);\n console.log(`Removed ${target}. Now running free tier.`);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n console.log(`No license file at ${target}; already on free tier.`);\n } else {\n throw err;\n }\n }\n });\n\n return cmd;\n}\n","/**\n * `ddt mcp` — Model Context Protocol server (stdio transport).\n *\n * Exposes DDT's read-only operations as MCP tools so AI agents (Claude\n * Desktop, Cursor, Continue, Claude Code, MCP-aware IDE plugins) can\n * call them. Speaks JSON-RPC 2.0 over newline-delimited JSON on stdio.\n *\n * To wire into Claude Desktop / Cursor / etc., add to the MCP config:\n *\n * {\n * \"mcpServers\": {\n * \"ddt\": { \"command\": \"ddt\", \"args\": [\"mcp\"] }\n * }\n * }\n *\n * Tools exposed:\n * - ddt.validate — schema check on a .ddtproj\n * - ddt.compare — pac↔pac diff (offline)\n * - ddt.docs — generate HTML schema docs\n * - ddt.erd — generate Mermaid ER diagram (Markdown)\n * - ddt.safety_assess — classify a diff's safety findings\n * - ddt.narrate_diff — structured payload (diff + safety + prompt\n * scaffold) so the calling agent's LLM can\n * generate a plain-English narration.\n * - ddt.detect_pii — scan a project/pac for likely PII columns.\n * - ddt.suggest_safer — saferAlternatives entries for every\n * UNRECOVERABLE / DESTRUCTIVE finding.\n * - ddt.feature_search — search the DDT feature catalog by keyword.\n *\n * Live-network tools (extract, publish) are deliberately NOT exposed\n * — they require profile credentials and we'd rather an agent not act\n * on those without explicit user invocation.\n */\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport {\n CompareEngine,\n PacSource,\n renderDocsReport,\n renderErdMarkdown,\n loadProject,\n parseProjectModel,\n discoverObjectFiles,\n pac,\n pii,\n safety,\n features,\n type DatabricksObject,\n} from '@ddt-tools/core';\n\ninterface JsonRpcRequest {\n jsonrpc: '2.0';\n id?: number | string | null;\n method: string;\n params?: unknown;\n}\n\ninterface JsonRpcResponse {\n jsonrpc: '2.0';\n id: number | string | null;\n result?: unknown;\n error?: { code: number; message: string; data?: unknown };\n}\n\nconst SERVER_NAME = 'ddt';\nconst SERVER_VERSION = '0.2.0';\nconst PROTOCOL_VERSION = '2024-11-05';\n\ninterface ToolDef {\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n handler: (args: Record<string, unknown>) => Promise<string>;\n}\n\nconst TOOLS: ToolDef[] = [\n {\n name: 'ddt.validate',\n description:\n 'Validate a .ddtproj file: parse JSON, check schema with zod, list object files. Returns a JSON summary of project structure.',\n inputSchema: {\n type: 'object',\n properties: {\n projectPath: { type: 'string', description: 'Absolute path to a .ddtproj file.' },\n },\n required: ['projectPath'],\n },\n handler: async (args) => {\n const projectPath = path.resolve(String(args.projectPath));\n const loaded = await loadProject(projectPath);\n const files = await discoverObjectFiles(loaded);\n return JSON.stringify(\n {\n ok: true,\n name: loaded.project.name,\n version: loaded.project.version,\n scope: loaded.project.scope,\n objectFileCount: files.length,\n profiles: Object.keys(loaded.project.deploymentProfiles ?? {}),\n },\n null,\n 2,\n );\n },\n },\n {\n name: 'ddt.compare',\n description:\n 'Compare two .ddtpac files (offline). Returns the diff JSON: added / removed / modified objects, with per-object field changes.',\n inputSchema: {\n type: 'object',\n properties: {\n sourcePac: { type: 'string', description: 'Absolute path to the source .ddtpac.' },\n targetPac: { type: 'string', description: 'Absolute path to the target .ddtpac.' },\n },\n required: ['sourcePac', 'targetPac'],\n },\n handler: async (args) => {\n const source = new PacSource(path.resolve(String(args.sourcePac)));\n const target = new PacSource(path.resolve(String(args.targetPac)));\n const engine = new CompareEngine();\n const result = await engine.compare(source, target);\n return JSON.stringify(result, null, 2);\n },\n },\n {\n name: 'ddt.docs',\n description:\n 'Generate self-contained HTML schema documentation from a .ddtproj or .ddtpac. Returns the HTML body as a string.',\n inputSchema: {\n type: 'object',\n properties: {\n source: { type: 'string', description: 'Absolute path to a .ddtproj or .ddtpac.' },\n title: { type: 'string', description: 'Optional doc title.' },\n },\n required: ['source'],\n },\n handler: async (args) => {\n const model = await loadModel(String(args.source));\n return renderDocsReport(model, {\n title: typeof args.title === 'string' ? args.title : 'Schema docs',\n });\n },\n },\n {\n name: 'ddt.erd',\n description: 'Generate a Mermaid ER diagram (Markdown) from a .ddtproj or .ddtpac.',\n inputSchema: {\n type: 'object',\n properties: {\n source: { type: 'string', description: 'Absolute path to a .ddtproj or .ddtpac.' },\n title: { type: 'string', description: 'Optional diagram title.' },\n },\n required: ['source'],\n },\n handler: async (args) => {\n const model = await loadModel(String(args.source));\n return renderErdMarkdown(\n model,\n typeof args.title === 'string' ? args.title : 'Schema ER diagram',\n );\n },\n },\n {\n name: 'ddt.safety_assess',\n description:\n 'Given two .ddtpac files, run the safety classifier on the diff. Returns UNRECOVERABLE / DESTRUCTIVE / EXPENSIVE / WARNING findings with the gate option each would need.',\n inputSchema: {\n type: 'object',\n properties: {\n sourcePac: { type: 'string', description: 'Source .ddtpac (desired state).' },\n targetPac: { type: 'string', description: 'Target .ddtpac (current state).' },\n },\n required: ['sourcePac', 'targetPac'],\n },\n handler: async (args) => {\n const source = new PacSource(path.resolve(String(args.sourcePac)));\n const target = new PacSource(path.resolve(String(args.targetPac)));\n const engine = new CompareEngine();\n const diff = await engine.compare(source, target);\n const assessment = safety.assess(diff);\n return JSON.stringify(assessment, null, 2);\n },\n },\n {\n name: 'ddt.narrate_diff',\n description:\n \"Build a structured payload (diff summary + per-object changes + safety findings + a system-prompt scaffold) the calling agent's LLM can use to generate a plain-English narration of a schema diff. Returns JSON the agent should compose into its own completion.\",\n inputSchema: {\n type: 'object',\n properties: {\n sourcePac: { type: 'string', description: 'Source .ddtpac (desired state).' },\n targetPac: { type: 'string', description: 'Target .ddtpac (current state).' },\n },\n required: ['sourcePac', 'targetPac'],\n },\n handler: async (args) => {\n const source = new PacSource(path.resolve(String(args.sourcePac)));\n const target = new PacSource(path.resolve(String(args.targetPac)));\n const engine = new CompareEngine();\n const diff = await engine.compare(source, target);\n const assessment = safety.assess(diff);\n const payload = {\n summary: diff.summary,\n objects: diff.objects.map((o) => ({\n kind: o.kind,\n objectType: o.identity.objectType,\n fqn: o.identity.fqn,\n })),\n safety: assessment,\n promptScaffold: {\n system:\n 'You are a senior Databricks UC engineer reviewing a schema migration. ' +\n 'Narrate the change in 2-3 short paragraphs: (1) the intent, ' +\n '(2) the safest order of operations, (3) the risks to watch ' +\n 'for. Be concrete; reference the FQNs.',\n userTemplate: 'Here is the diff JSON and the safety assessment. Generate the narration.',\n },\n };\n return JSON.stringify(payload, null, 2);\n },\n },\n {\n name: 'ddt.detect_pii',\n description:\n 'Scan a project or pac for columns that look like PII (email, phone, ssn, dob, credit-card, national-id, health, ip-address, name, address, generic). Returns each candidate with its category, confidence tier, and the reason the heuristic flagged it.',\n inputSchema: {\n type: 'object',\n properties: {\n source: { type: 'string', description: 'Absolute path to a .ddtproj or .ddtpac.' },\n },\n required: ['source'],\n },\n handler: async (args) => {\n const model = await loadModel(String(args.source));\n const candidates = pii.detectPiiCandidates(model);\n return JSON.stringify({ count: candidates.length, candidates }, null, 2);\n },\n },\n {\n name: 'ddt.suggest_safer',\n description:\n 'For every UNRECOVERABLE / DESTRUCTIVE finding the safety classifier produced on a diff, return the catalog\\'s saferAlternatives entries (e.g. \"instead of DROP TABLE, RENAME with a date suffix and let the retention policy expire it\"). The agent can paste these into a PR comment or CodeLens suggestion.',\n inputSchema: {\n type: 'object',\n properties: {\n sourcePac: { type: 'string', description: 'Source .ddtpac (desired).' },\n targetPac: { type: 'string', description: 'Target .ddtpac (current).' },\n },\n required: ['sourcePac', 'targetPac'],\n },\n handler: async (args) => {\n const source = new PacSource(path.resolve(String(args.sourcePac)));\n const target = new PacSource(path.resolve(String(args.targetPac)));\n const engine = new CompareEngine();\n const diff = await engine.compare(source, target);\n const assessment = safety.assess(diff);\n const dangerous = [...assessment.unrecoverable, ...assessment.destructive];\n const suggestions = dangerous.map((f) => {\n const explanation = safety.explainFinding(f.code);\n return {\n finding: { code: f.code, category: f.category, fqn: f.fqn, reason: f.reason },\n saferAlternatives: explanation?.saferAlternatives ?? [],\n requiredGates: explanation?.requiredGates ?? [],\n };\n });\n return JSON.stringify({ count: suggestions.length, suggestions }, null, 2);\n },\n },\n {\n name: 'ddt.feature_search',\n description:\n 'Search the DDT feature catalog by keyword. Returns features whose id, name, summary, or synonyms match the query. Useful for discovering which tier unlocks a capability or finding the right command for a task.',\n inputSchema: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description:\n 'Search term — feature name, keyword, or capability (e.g. \"drift\", \"slice\", \"AI\").',\n },\n },\n required: ['query'],\n },\n handler: async (args) => {\n const q = String(args.query ?? '')\n .toLowerCase()\n .trim();\n const matches = features.DDT_FEATURE_CATALOG.filter(\n (f) =>\n f.id.includes(q) ||\n f.name.toLowerCase().includes(q) ||\n f.summary.toLowerCase().includes(q) ||\n f.synonyms?.some((s) => s.toLowerCase().includes(q)) ||\n f.whenToUse?.toLowerCase().includes(q),\n );\n return JSON.stringify(\n {\n count: matches.length,\n features: matches.map((f) => ({\n id: f.id,\n name: f.name,\n tier: f.tier,\n status: f.status,\n summary: f.summary,\n unlockHow: f.unlockHow,\n useCases: f.useCases,\n relatedFeatures: f.relatedFeatures,\n })),\n },\n null,\n 2,\n );\n },\n },\n];\n\nasync function loadModel(sourcePath: string): Promise<DatabricksObject[]> {\n const abs = path.resolve(sourcePath);\n if (abs.endsWith('.ddtpac')) {\n const pacContents = await pac.readPac(abs);\n return pacContents.model;\n }\n const loaded = await loadProject(abs);\n const parsed = await parseProjectModel(loaded);\n return parsed as DatabricksObject[];\n}\n\nexport function mcpCommand(): Command {\n const cmd = new Command('mcp');\n cmd\n .description(\n 'Start the DDT Model Context Protocol server on stdio (for Claude / Cursor / agents).',\n )\n .action(async () => {\n await runMcpStdio();\n });\n return cmd;\n}\n\nasync function runMcpStdio(): Promise<void> {\n await new Promise<void>((resolve) => {\n let buffer = '';\n process.stdin.setEncoding('utf8');\n process.stdin.on('data', (chunk: string) => {\n buffer += chunk;\n let nl = buffer.indexOf('\\n');\n while (nl !== -1) {\n const line = buffer.slice(0, nl).trim();\n buffer = buffer.slice(nl + 1);\n if (line.length > 0) {\n void handleLine(line);\n }\n nl = buffer.indexOf('\\n');\n }\n });\n process.stdin.on('end', () => resolve());\n process.stdin.on('close', () => resolve());\n });\n}\n\nasync function handleLine(line: string): Promise<void> {\n let req: JsonRpcRequest;\n try {\n req = JSON.parse(line) as JsonRpcRequest;\n } catch (err) {\n send({\n jsonrpc: '2.0',\n id: null,\n error: { code: -32700, message: 'Parse error', data: String(err) },\n });\n return;\n }\n const id = req.id ?? null;\n try {\n const result = await dispatch(req);\n if (id !== null) {\n send({ jsonrpc: '2.0', id, result });\n }\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n send({ jsonrpc: '2.0', id, error: { code: -32603, message } });\n }\n}\n\nasync function dispatch(req: JsonRpcRequest): Promise<unknown> {\n switch (req.method) {\n case 'initialize':\n return {\n protocolVersion: PROTOCOL_VERSION,\n serverInfo: { name: SERVER_NAME, version: SERVER_VERSION },\n capabilities: { tools: {} },\n };\n case 'notifications/initialized':\n return undefined;\n case 'tools/list':\n return {\n tools: TOOLS.map((t) => ({\n name: t.name,\n description: t.description,\n inputSchema: t.inputSchema,\n })),\n };\n case 'tools/call': {\n const params = (req.params ?? {}) as { name?: string; arguments?: Record<string, unknown> };\n const tool = TOOLS.find((t) => t.name === params.name);\n if (!tool) throw new Error(`Unknown tool: ${String(params.name)}`);\n const output = await tool.handler(params.arguments ?? {});\n return { content: [{ type: 'text', text: output }] };\n }\n case 'ping':\n return {};\n default:\n throw new Error(`Method not found: ${req.method}`);\n }\n}\n\nfunction send(msg: JsonRpcResponse): void {\n process.stdout.write(`${JSON.stringify(msg)}\\n`);\n}\n","/**\n * `ddt ai` — configure + test the AI provider adapter.\n *\n * Subcommands:\n * ddt ai status — show current config (provider, model, key source)\n * ddt ai test — round-trip a hello-world prompt\n * ddt ai usage — summarize ai-usage.json (today + this month)\n *\n * Phase-1 of the AI rollout (see docs/AI_FEATURES.md). Mirrors\n * `sdt ai` — same subcommands, same shape, only the default config\n * path differs (`~/.config/ddt/ai.json`).\n */\nimport { Command } from 'commander';\nimport { ai } from '@ddt-tools/core';\n\nexport function aiCommand(): Command {\n const cmd = new Command('ai');\n cmd.description('Configure and test the AI provider adapter (BYO key).');\n\n cmd\n .command('status')\n .description('Show the resolved AI provider config (provider, model, key source).')\n .action(async () => {\n const config = await ai.resolveAiConfig();\n const apiKey = ai.resolveApiKey(config);\n console.log('AI provider config (configured):');\n console.log(` provider: ${config.provider}`);\n console.log(` model: ${config.model}`);\n console.log(` endpoint: ${config.endpoint ?? '(provider default)'}`);\n console.log(` apiKey: ${apiKey ? '✓ resolved' : '✗ not set'}`);\n console.log(` maxTokens: ${config.maxTokens ?? '(provider default)'}`);\n console.log(` temperature: ${config.temperature ?? '(provider default)'}`);\n console.log(\n ` preferLocal: ${config.preferLocal !== false ? 'true (local-first)' : 'false (cloud only)'}`,\n );\n console.log(` configPath: ${ai.defaultConfigPath()}`);\n\n if (config.preferLocal !== false) {\n const probe = await ai.detectOllamaAvailability({ fetch: globalThis.fetch });\n console.log('Local Ollama probe:');\n if (probe.available) {\n const best = ai.pickBestLocalModel(probe.models);\n console.log(` status: ✓ available at ${probe.endpoint}`);\n console.log(` models: ${probe.models.join(', ') || '(none pulled)'}`);\n console.log(` selected: ${best ?? '(none)'}`);\n console.log('Effective routing: Ollama (local, zero cloud cost)');\n } else {\n console.log(` status: ✗ unavailable (${probe.reason})`);\n console.log(` fallback: ${config.provider} / ${config.model}`);\n console.log(`Effective routing: ${config.provider} (cloud)`);\n }\n }\n });\n\n cmd\n .command('test')\n .description('Round-trip a small prompt against the configured provider.')\n .option('--prompt <text>', 'Prompt to send.', 'Reply with exactly the four characters: PONG')\n .option(\n '--ai-max-spend <usd>',\n \"Refuse the call if today's estimated spend ≥ this (USD). 0 = no cap.\",\n '0',\n )\n .action(async (opts) => {\n const result = await ai.complete(\n [\n { role: 'system', content: 'You are a terse assistant. Follow instructions exactly.' },\n { role: 'user', content: String(opts.prompt) },\n ],\n {\n feature: 'ai.test',\n maxSpendUsd: Number(opts.aiMaxSpend ?? '0') || 0,\n },\n );\n console.log(`Response from ${result.provider} (${result.model}):`);\n console.log(result.text);\n console.log(\n ` tokens: ${result.usage.promptTokens} in / ${result.usage.completionTokens} out`,\n );\n });\n\n cmd\n .command('usage')\n .description('Summarize the local AI usage ledger.')\n .action(async () => {\n const records = await ai.readUsage();\n const today = ai.todayRecords(records);\n const todayUsd = ai.totalSpend(today);\n const allUsd = ai.totalSpend(records);\n console.log('AI usage (local ledger):');\n console.log(` today: ${today.length} call(s), ~$${todayUsd.toFixed(4)}`);\n console.log(` total: ${records.length} call(s), ~$${allUsd.toFixed(4)}`);\n console.log(` ledger: ${ai.defaultUsagePath()}`);\n if (records.length > 0) {\n const byFeature = new Map<string, number>();\n for (const r of records) {\n const key = r.feature ?? '(unknown)';\n byFeature.set(key, (byFeature.get(key) ?? 0) + 1);\n }\n console.log(' features:');\n for (const [feature, count] of [...byFeature.entries()].sort((a, b) => b[1] - a[1])) {\n console.log(` ${feature}: ${count}`);\n }\n }\n });\n\n return cmd;\n}\n","/**\n * `ddt explain <query>` — search the options catalog and print details.\n *\n * Examples:\n * ddt explain drop table\n * ddt explain allowNarrowingTypes\n * ddt explain --tag safety\n * ddt explain --safety destructive\n *\n * See `docs/UX_PLAYBOOK.md` §2 for the full design.\n */\nimport { Command } from 'commander';\nimport { options as optionsApi, type options as optionsNs } from '@ddt-tools/core';\n\ntype OptionEntry = optionsNs.OptionEntry;\ntype SafetyTier = optionsNs.SafetyTier;\n\nexport function explainCommand(): Command {\n const cmd = new Command('explain');\n cmd\n .description(\n 'Search the options catalog. Explains what an option does, when to use it, and what it pairs with.',\n )\n .argument('[query...]', 'Free-form search — flag name, alias, or text.')\n .option(\n '--tag <tag>',\n 'Filter by tag (e.g. compare, deployment, safety, drop, column, streaming, governance).',\n )\n .option(\n '--safety <tier>',\n 'Filter by safety tier (safe, review, data-impacting, destructive, unrecoverable).',\n )\n .option('--limit <n>', 'Max results to show.', '8')\n .option('--list', 'List all options grouped by tag.')\n .option('--format <fmt>', 'Output format: text | json | markdown. Default text.', 'text')\n .action(async (queryParts: string[], opts) => {\n const query = (queryParts ?? []).join(' ').trim();\n const limit = Number.parseInt(String(opts.limit ?? '8'), 10) || 8;\n const safety = opts.safety as SafetyTier | undefined;\n const tag = opts.tag as string | undefined;\n const fmt = String(opts.format ?? 'text').toLowerCase();\n\n if (opts.list) {\n const all = optionsApi.listOptions({ tag, safety });\n if (fmt === 'json') {\n console.log(JSON.stringify(all, null, 2));\n } else if (fmt === 'markdown') {\n console.log(renderMarkdownList(all));\n } else {\n printSummaryList(all);\n }\n return;\n }\n\n if (!query && !tag && !safety) {\n cmd.outputHelp();\n return;\n }\n\n const hits = optionsApi.searchOptions(query, { tag, safety, limit });\n if (hits.length === 0) {\n if (fmt === 'json') {\n console.log('[]');\n return;\n }\n console.warn(`No matches for: \"${query || `${tag ?? ''} ${safety ?? ''}`.trim()}\"`);\n console.warn(' Try: ddt explain --list');\n console.warn(' Try: ddt explain --tag safety');\n return;\n }\n\n if (fmt === 'json') {\n console.log(\n JSON.stringify(\n hits.map((h) => h.entry),\n null,\n 2,\n ),\n );\n return;\n }\n if (fmt === 'markdown') {\n for (const [i, hit] of hits.entries()) {\n if (i > 0) console.log('');\n console.log(renderMarkdownEntry(hit.entry));\n }\n return;\n }\n\n for (const [i, hit] of hits.entries()) {\n if (i > 0) console.log('');\n printEntry(hit.entry);\n }\n });\n return cmd;\n}\n\nfunction renderMarkdownEntry(entry: OptionEntry): string {\n const lines: string[] = [];\n const badge = entry.safety ? ` _(safety: ${entry.safety})_` : '';\n lines.push(`### \\`${entry.name}\\`${badge}`);\n lines.push('');\n lines.push(`**${entry.summary}**`);\n lines.push('');\n lines.push(`- **short**: ${entry.short}`);\n if (entry.aliases.length > 0)\n lines.push(`- **aliases**: ${entry.aliases.map((a) => `\\`${a}\\``).join(', ')}`);\n lines.push(`- **type**: \\`${entry.type}\\``);\n lines.push(`- **default**: \\`${entry.defaultValue}\\``);\n if (entry.enumValues)\n lines.push(`- **values**: ${entry.enumValues.map((v) => `\\`${v}\\``).join(', ')}`);\n lines.push(`- **path**: \\`${entry.path}\\``);\n lines.push(`- **tags**: ${entry.tags.map((t) => `\\`${t}\\``).join(', ')}`);\n if (entry.example) {\n lines.push('');\n lines.push('```');\n lines.push(entry.example);\n lines.push('```');\n }\n if (entry.details) {\n lines.push('');\n lines.push('**Details**:');\n lines.push('');\n for (const line of entry.details.split(/\\r?\\n/)) lines.push(`> ${line}`);\n }\n if (entry.worksWellWith && entry.worksWellWith.length > 0) {\n lines.push('');\n lines.push('**Works well with**:');\n for (const ref of entry.worksWellWith) lines.push(`- \\`${ref}\\``);\n }\n if (entry.conflictsWith && entry.conflictsWith.length > 0) {\n lines.push('');\n lines.push('**Conflicts with**:');\n for (const ref of entry.conflictsWith) lines.push(`- \\`${ref}\\``);\n }\n return lines.join('\\n');\n}\n\nfunction renderMarkdownList(entries: readonly OptionEntry[]): string {\n const grouped = new Map<string, OptionEntry[]>();\n for (const entry of entries) {\n const tag = entry.tags[0] ?? 'misc';\n const arr = grouped.get(tag) ?? [];\n arr.push(entry);\n grouped.set(tag, arr);\n }\n const lines: string[] = [];\n lines.push('# Options catalog');\n lines.push('');\n for (const tag of [...grouped.keys()].sort()) {\n lines.push(`## ${tag} (${grouped.get(tag)!.length})`);\n lines.push('');\n for (const e of grouped.get(tag)!) {\n const badge = e.safety ? ` _(${e.safety})_` : '';\n lines.push(`- \\`${e.short}\\`${badge} — ${e.summary}`);\n }\n lines.push('');\n }\n return lines.join('\\n');\n}\n\nfunction printEntry(entry: OptionEntry): void {\n const tags = entry.tags.join(', ');\n const safetyBadge = entry.safety ? ` [safety: ${entry.safety}]` : '';\n console.log(`${entry.name}${safetyBadge}`);\n console.log(` short: ${entry.short}`);\n if (entry.aliases.length > 0) {\n console.log(` aliases: ${entry.aliases.join(', ')}`);\n }\n console.log(` type: ${entry.type}`);\n console.log(` default: ${entry.defaultValue}`);\n if (entry.enumValues) console.log(` values: ${entry.enumValues.join(', ')}`);\n console.log(` path: ${entry.path}`);\n console.log(` tags: ${tags}`);\n console.log(` summary: ${entry.summary}`);\n console.log(` details:`);\n for (const line of entry.details.split(/\\r?\\n/)) {\n console.log(` ${line}`);\n }\n if (entry.example) {\n console.log(` example: ${entry.example}`);\n }\n if (entry.worksWellWith && entry.worksWellWith.length > 0) {\n console.log(` works well with:`);\n for (const ref of entry.worksWellWith) console.log(` - ${ref}`);\n }\n if (entry.conflictsWith && entry.conflictsWith.length > 0) {\n console.log(` conflicts with:`);\n for (const ref of entry.conflictsWith) console.log(` - ${ref}`);\n }\n if (entry.seeAlso && entry.seeAlso.length > 0) {\n console.log(` see also: ${entry.seeAlso.join(', ')}`);\n }\n}\n\nfunction printSummaryList(entries: readonly OptionEntry[]): void {\n const grouped = new Map<string, OptionEntry[]>();\n for (const entry of entries) {\n const tag = entry.tags[0] ?? 'misc';\n const arr = grouped.get(tag) ?? [];\n arr.push(entry);\n grouped.set(tag, arr);\n }\n const tagOrder = [...grouped.keys()].sort();\n for (const tag of tagOrder) {\n console.log(`# ${tag} (${grouped.get(tag)!.length})`);\n for (const e of grouped.get(tag)!) {\n const badge = e.safety ? ` [${e.safety}]` : '';\n console.log(` ${e.short}${badge}`);\n console.log(` ${e.summary}`);\n }\n console.log('');\n }\n}\n","/**\n * `ddt feedback \"...\"` — submit a feedback / bug / feature-request\n * ticket from inside the tool.\n *\n * Sibling of `sdt feedback`. Same shape; different default\n * file paths (`~/.ddt/...`) + default URL.\n *\n * See `docs/SUPPORT_OPERATIONS.md` for the ingest pipeline.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport os from 'node:os';\nimport { Command } from 'commander';\nimport { license } from '@ddt-tools/core';\n\nconst DEFAULT_INGEST_URL =\n process.env.DDT_FEEDBACK_URL ?? 'https://sdt-support.sdt-ddt-tools.workers.dev/ingest';\nconst OUTBOX_DIR = path.join(os.homedir(), '.ddt', 'feedback');\n\ninterface FeedbackPayload {\n body: string;\n product: 'sdt' | 'ddt';\n productVersion: string;\n os: string;\n nodeVersion: string;\n ts: string;\n contact?: string;\n licenseEmail?: string;\n recentCommands?: string[];\n category?: 'bug' | 'feature' | 'question' | 'docs' | 'other';\n}\n\nexport function feedbackCommand(): Command {\n const cmd = new Command('feedback');\n cmd\n .description('Send a feedback / bug / feature-request ticket to the DDT team.')\n .argument('<message...>', 'The feedback body (quote to keep as one arg).')\n .option('--category <kind>', 'Category: bug | feature | question | docs | other', 'other')\n .option(\n '--contact <email>',\n 'Reply-to email (optional; otherwise we use the license email if any).',\n )\n .option('--no-context', 'Skip auto-capture of CLI version / OS / recent commands.')\n .option('--dry-run', 'Print the payload without sending or queueing.')\n .option('--url <url>', `Override the ingest endpoint. Default ${DEFAULT_INGEST_URL}.`)\n .action(async (messageParts: string[], opts) => {\n const body = (messageParts ?? []).join(' ').trim();\n if (!body) {\n console.error('Empty feedback body — nothing to send.');\n process.exitCode = 1;\n return;\n }\n const payload = await buildPayload(body, opts);\n if (opts.dryRun) {\n console.log(JSON.stringify(payload, null, 2));\n return;\n }\n try {\n await sendOrQueue(payload, String(opts.url ?? DEFAULT_INGEST_URL));\n console.log('Feedback sent. Thank you!');\n console.log(' You should hear back within 1 business day for Pro+ accounts.');\n if (!payload.licenseEmail) {\n console.log(' Tip: install a license (`ddt license activate`) so we can reach you.');\n }\n const extended = await license.extendTrial(1);\n if (extended) {\n console.log(\n ` Feedback bonus: +1 trial day (now expires ${extended.expiresAt.slice(0, 10)}).`,\n );\n }\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n console.warn(`Couldn't reach the ingest endpoint: ${message}`);\n const queued = await queueLocally(payload);\n console.log(` Queued locally at ${queued}. Will retry on next \\`ddt feedback\\` run.`);\n }\n });\n return cmd;\n}\n\nasync function buildPayload(\n body: string,\n opts: { category?: string; contact?: string; context?: boolean },\n): Promise<FeedbackPayload> {\n const category = normalizeCategory(opts.category);\n const payload: FeedbackPayload = {\n body,\n product: 'ddt',\n productVersion: await readCliVersion(),\n os: `${os.platform()} ${os.release()}`,\n nodeVersion: process.version,\n ts: new Date().toISOString(),\n category,\n };\n if (opts.contact) payload.contact = String(opts.contact);\n if (opts.context !== false) {\n payload.licenseEmail = await readLicenseEmail();\n payload.recentCommands = await readRecentCommands();\n }\n return payload;\n}\n\nasync function readCliVersion(): Promise<string> {\n try {\n const pkgPath = path.join(\n path.dirname(new URL(import.meta.url).pathname),\n '..',\n '..',\n 'package.json',\n );\n const raw = await fs.readFile(pkgPath, 'utf8');\n const obj = JSON.parse(raw) as { version?: string };\n return obj.version ?? 'unknown';\n } catch {\n return 'unknown';\n }\n}\n\nasync function readLicenseEmail(): Promise<string | undefined> {\n try {\n const licensePath = path.join(os.homedir(), '.ddt', 'license');\n const raw = await fs.readFile(licensePath, 'utf8');\n const parts = raw.trim().split('.');\n if (parts.length < 2) return undefined;\n const payload: unknown = JSON.parse(Buffer.from(parts[1]!, 'base64url').toString('utf8'));\n if (typeof payload === 'object' && payload !== null) {\n const sub = (payload as { sub?: unknown }).sub;\n if (typeof sub === 'string') return sub;\n }\n return undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function readRecentCommands(): Promise<string[] | undefined> {\n try {\n const logPath = path.join(os.homedir(), '.ddt', 'recent.log');\n const raw = await fs.readFile(logPath, 'utf8');\n return raw.split(/\\r?\\n/).filter(Boolean).slice(-5);\n } catch {\n return undefined;\n }\n}\n\nfunction normalizeCategory(input: unknown): FeedbackPayload['category'] {\n const s = String(input ?? 'other').toLowerCase();\n if (s === 'bug' || s === 'feature' || s === 'question' || s === 'docs') return s;\n return 'other';\n}\n\nasync function sendOrQueue(payload: FeedbackPayload, url: string): Promise<void> {\n await drainOutbox(url);\n const res = await fetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(payload),\n });\n if (!res.ok) {\n throw new Error(`HTTP ${res.status}`);\n }\n}\n\nasync function queueLocally(payload: FeedbackPayload): Promise<string> {\n await fs.mkdir(OUTBOX_DIR, { recursive: true });\n const file = path.join(OUTBOX_DIR, `${Date.now()}-${randomTag()}.json`);\n await fs.writeFile(file, JSON.stringify(payload, null, 2));\n return file;\n}\n\nasync function drainOutbox(url: string): Promise<void> {\n try {\n const entries = await fs.readdir(OUTBOX_DIR);\n for (const entry of entries) {\n if (!entry.endsWith('.json')) continue;\n const file = path.join(OUTBOX_DIR, entry);\n try {\n const raw = await fs.readFile(file, 'utf8');\n const res = await fetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: raw,\n });\n if (res.ok) {\n await fs.unlink(file);\n }\n } catch {\n // Keep in outbox; will retry next time.\n }\n }\n } catch {\n // No outbox; nothing to drain.\n }\n}\n\nfunction randomTag(): string {\n return Math.random().toString(36).slice(2, 8);\n}\n","/**\n * `ddt features` — browse the DDT feature catalog regardless of tier.\n *\n * The point: every user can see every feature, with copy that explains\n * what it does and exactly what would unlock it. Better UX than silent\n * gates (\"why doesn't `--map-rewrite-strings` work?\") or surprise\n * paywalls at the command line.\n *\n * Subcommands:\n * ddt features list Show all features with state (✅ / 🔒 / 🚧).\n * ddt features show <id> Full pitch + unlock path for one feature.\n * ddt features upgrade What each paid tier would unlock for you.\n */\nimport { Command } from 'commander';\nimport { features as featuresApi, license as licenseApi } from '@ddt-tools/core';\n\nexport function featuresCommand(): Command {\n const cmd = new Command('features');\n cmd.description(\n 'Browse DDT features. Free users see paid features too — with copy explaining what each one does and how to unlock it.',\n );\n\n cmd\n .command('list')\n .description('List every feature with its tier and your current access state.')\n .action(async () => {\n const license = await licenseApi.loadLicense();\n const rows = featuresApi.listFeatureAvailability(license);\n\n const nameWidth = Math.max(...rows.map((r) => r.feature.name.length), 4);\n\n let lastTier = '';\n for (const row of rows) {\n if (row.feature.tier !== lastTier) {\n if (lastTier !== '') process.stdout.write('\\n');\n process.stdout.write(`── ${row.feature.tier.toUpperCase()} ──\\n`);\n lastTier = row.feature.tier;\n }\n const pad = (s: string, w: number): string => s + ' '.repeat(Math.max(0, w - s.length));\n process.stdout.write(\n ` ${pad(row.state, 22)} ${pad(row.feature.name, nameWidth)} ${row.feature.summary}\\n`,\n );\n }\n process.stdout.write(\n '\\nRun `ddt features show <id>` for the full pitch. `ddt features upgrade` shows the path to the next tier.\\n',\n );\n });\n\n cmd\n .command('show <id>')\n .description('Print the full pitch + unlock path for one feature.')\n .action(async (id: string) => {\n const feature = featuresApi.getFeature(id);\n if (!feature) {\n console.error(`Unknown feature id: \"${id}\". Run \\`ddt features list\\` to see all ids.`);\n process.exitCode = 1;\n return;\n }\n const license = await licenseApi.loadLicense();\n const available = featuresApi.isFeatureAvailable(feature, license);\n const body = available\n ? featuresApi.unlockedFeatureMessage(feature)\n : featuresApi.lockedFeatureMessage(feature);\n process.stdout.write(body + '\\n');\n });\n\n cmd\n .command('upgrade')\n .description('Show what each paid tier would unlock for your current license.')\n .action(async () => {\n const license = await licenseApi.loadLicense();\n process.stdout.write(featuresApi.upgradeSummary(license) + '\\n');\n });\n\n return cmd;\n}\n","/**\n * `ddt hosts` — browse every host DDT plugs into, with version-support\n * + tailoring notes. Companion to `ddt features`: features tell you\n * what we do; hosts tell you where you can do it.\n */\nimport { Command } from 'commander';\nimport { hosts as hostsApi } from '@ddt-tools/core';\n\nexport function hostsCommand(): Command {\n const cmd = new Command('hosts');\n cmd.description(\n 'Browse every host DDT plugs into — CLI, VS Code, MCP agents, Databricks Workflows, dbt, Airflow, etc. Shows supported versions and the host-specific tailoring notes.',\n );\n\n cmd\n .command('list')\n .description('List every host adapter with its status and version range.')\n .action(() => {\n const rows = hostsApi.listHosts();\n const nameWidth = Math.max(...rows.map((h) => h.name.length), 4);\n let lastKind = '';\n for (const host of rows) {\n if (host.kind !== lastKind) {\n if (lastKind !== '') process.stdout.write('\\n');\n process.stdout.write(`── ${host.kind.toUpperCase()} ──\\n`);\n lastKind = host.kind;\n }\n const pad = (s: string, w: number): string => s + ' '.repeat(Math.max(0, w - s.length));\n const versions = hostsApi.hostSummaryLine(host).split(' · ')[1] ?? '';\n process.stdout.write(` ${pad(host.name, nameWidth)} ${versions}\\n`);\n }\n process.stdout.write(\n '\\nRun `ddt hosts show <id>` for tailoring notes. See docs/HOST_INTEGRATIONS.md for the per-host playbook.\\n',\n );\n });\n\n cmd\n .command('show <id>')\n .description('Print supported versions, idioms, and tailoring notes for one host.')\n .action((id: string) => {\n const host = hostsApi.getHost(id);\n if (!host) {\n console.error(`Unknown host id: \"${id}\". Run \\`ddt hosts list\\` to see all ids.`);\n process.exitCode = 1;\n return;\n }\n process.stdout.write(hostsApi.hostDetailMessage(host) + '\\n');\n });\n\n return cmd;\n}\n","/**\n * `ddt safety` — inspect safety-finding codes.\n *\n * Subcommands:\n * ddt safety list — list every known finding code with a one-line summary\n * ddt safety explain <code> — deep explainer for a single code: why it is dangerous,\n * what cannot be reversed, safer alternatives, required gates\n *\n * The finding codes are stable identifiers attached to every `SafetyFinding`\n * the classifier emits during `ddt compare` / `ddt publish`. When the user\n * sees a finding they don't understand, they can copy the code and ask:\n *\n * ddt safety explain DROP_UNRECOVERABLE\n *\n * Mirrors `Snowflake/packages/cli/src/commands/safety.ts` — paired-file rule.\n * See `docs/UX_PLAYBOOK.md` §3 (dangerous-op UX) and\n * `docs/AI_FEATURES.md` use case C2.\n */\nimport { Command } from 'commander';\nimport { safety as safetyApi, type safety as safetyNs } from '@ddt-tools/core';\n\ntype FindingExplanation = safetyNs.FindingExplanation;\ntype SafetyFindingCode = safetyNs.SafetyFindingCode;\n\nexport function safetyCommand(): Command {\n const cmd = new Command('safety');\n cmd.description(\n 'Inspect the safety-finding catalog. See `ddt safety list` and `ddt safety explain <code>`.',\n );\n\n cmd\n .command('list')\n .description('List every known finding code with category + one-line summary.')\n .option('--format <format>', 'Output format: table | json', 'table')\n .option(\n '--category <kind>',\n 'Filter to one category: unrecoverable | destructive | expensive | warning. Default: all.',\n )\n .action((opts: { format?: string; category?: string }) => {\n const codes = safetyApi.listFindingCodes();\n let entries = codes\n .map((c) => safetyApi.explainFinding(c))\n .filter((e): e is FindingExplanation => e !== undefined);\n if (opts.category) {\n const want = opts.category.toUpperCase();\n const valid = ['UNRECOVERABLE', 'DESTRUCTIVE', 'EXPENSIVE', 'WARNING'];\n if (!valid.includes(want)) {\n console.error(\n `Unknown --category \"${opts.category}\". Use one of: ${valid.join(' | ').toLowerCase()}.`,\n );\n process.exitCode = 1;\n return;\n }\n entries = entries.filter((e) => e.category === want);\n }\n if ((opts.format ?? 'table') === 'json') {\n process.stdout.write(JSON.stringify(entries, null, 2) + '\\n');\n return;\n }\n if (entries.length === 0) {\n console.log('(no entries match the filter)');\n return;\n }\n printList(entries);\n });\n\n cmd\n .command('explain')\n .description('Expand a finding code into a deep \"why this is dangerous\" page.')\n .argument('<code>', 'The finding code (e.g. DROP_UNRECOVERABLE, COLUMN_TYPE_CHANGE)')\n .option('--format <format>', 'Output format: text | json | markdown', 'text')\n .action((codeArg: string, opts: { format?: string }) => {\n const code = codeArg.toUpperCase() as SafetyFindingCode;\n const entry = safetyApi.explainFinding(code);\n if (!entry) {\n console.error(`Unknown safety finding code: \"${codeArg}\"`);\n console.error(' Try: ddt safety list');\n process.exitCode = 1;\n return;\n }\n const format = (opts.format ?? 'text').toLowerCase();\n if (format === 'json') {\n process.stdout.write(JSON.stringify(entry, null, 2) + '\\n');\n return;\n }\n if (format === 'markdown') {\n process.stdout.write(renderMarkdown(entry) + '\\n');\n return;\n }\n printDeep(entry);\n });\n\n return cmd;\n}\n\nfunction printList(entries: readonly FindingExplanation[]): void {\n const byCategory = new Map<FindingExplanation['category'], FindingExplanation[]>();\n for (const e of entries) {\n const arr = byCategory.get(e.category) ?? [];\n arr.push(e);\n byCategory.set(e.category, arr);\n }\n const order: FindingExplanation['category'][] = [\n 'UNRECOVERABLE',\n 'DESTRUCTIVE',\n 'EXPENSIVE',\n 'WARNING',\n ];\n for (const cat of order) {\n const arr = byCategory.get(cat);\n if (!arr || arr.length === 0) continue;\n console.log(`# ${cat} (${arr.length})`);\n for (const e of arr) {\n console.log(` ${e.code}`);\n console.log(` ${e.title}`);\n console.log(` ${e.summary}`);\n }\n console.log('');\n }\n console.log('Use `ddt safety explain <code>` for the full per-finding write-up.');\n}\n\nfunction printDeep(entry: FindingExplanation): void {\n console.log(`${entry.code} [${entry.category}]`);\n console.log(entry.title);\n console.log('');\n console.log('Summary');\n console.log(` ${entry.summary}`);\n console.log('');\n console.log('Why this is dangerous');\n for (const line of wrap(entry.whyDangerous, 76)) {\n console.log(` ${line}`);\n }\n console.log('');\n console.log('What cannot be reversed');\n for (const item of entry.cannotBeReversed) console.log(` - ${item}`);\n console.log('');\n console.log('Safer alternatives');\n for (const item of entry.saferAlternatives) console.log(` - ${item}`);\n console.log('');\n if (entry.requiredGates.length > 0) {\n console.log('Required gates to allow this finding through');\n for (const g of entry.requiredGates) console.log(` - ${g}`);\n console.log('');\n }\n if (entry.example) {\n console.log('Example');\n console.log(` ${entry.example}`);\n }\n}\n\nfunction renderMarkdown(entry: FindingExplanation): string {\n const lines: string[] = [];\n lines.push(`## ${entry.code} — ${entry.title}`);\n lines.push('');\n lines.push(`**Category:** ${entry.category}`);\n lines.push('');\n lines.push(`**Summary:** ${entry.summary}`);\n lines.push('');\n lines.push('### Why this is dangerous');\n lines.push(entry.whyDangerous);\n lines.push('');\n lines.push('### What cannot be reversed');\n for (const item of entry.cannotBeReversed) lines.push(`- ${item}`);\n lines.push('');\n lines.push('### Safer alternatives');\n for (const item of entry.saferAlternatives) lines.push(`- ${item}`);\n if (entry.requiredGates.length > 0) {\n lines.push('');\n lines.push('### Required gates');\n for (const g of entry.requiredGates) lines.push(`- \\`${g}\\``);\n }\n if (entry.example) {\n lines.push('');\n lines.push('### Example');\n lines.push('```');\n lines.push(entry.example);\n lines.push('```');\n }\n return lines.join('\\n');\n}\n\nfunction wrap(text: string, width: number): string[] {\n const words = text.split(/\\s+/);\n const lines: string[] = [];\n let current = '';\n for (const word of words) {\n if (current.length === 0) {\n current = word;\n } else if (current.length + 1 + word.length <= width) {\n current += ' ' + word;\n } else {\n lines.push(current);\n current = word;\n }\n }\n if (current.length > 0) lines.push(current);\n return lines;\n}\n","/**\n * `ddt pii` — scan a project for PII columns and optionally generate\n * Unity-Catalog column-mask DDL. Wraps `@ddt-tools/core/pii`.\n *\n * Mirrors `sdt pii`.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport {\n ai,\n loadProject,\n pac,\n parseProjectModel,\n pii,\n type DatabricksObject,\n} from '@ddt-tools/core';\n\nexport function piiCommand(): Command {\n const cmd = new Command('pii');\n cmd.description(\n 'Detect PII columns + render Unity-Catalog column-mask DDL. See `ddt pii scan` and `ddt pii mask`.',\n );\n\n cmd\n .command('scan')\n .description('Scan the project for PII column candidates.')\n .requiredOption('--source <path>', '.ddtproj or .ddtpac to scan.')\n .option('--format <fmt>', 'table | json | markdown. Default table.', 'table')\n .option(\n '--ai',\n 'Route low/medium-confidence candidates through the configured AI provider for verification.',\n false,\n )\n .option(\n '--verify-at-or-below <tier>',\n 'When --ai is on, verify candidates at or below this tier (high | medium | low).',\n 'medium',\n )\n .option('-o, --out <path>', 'Output file path. Defaults to stdout.')\n .action(\n async (opts: {\n source: string;\n format?: string;\n ai?: boolean;\n verifyAtOrBelow?: string;\n out?: string;\n }) => {\n const sourcePath = String(opts.source);\n const model = await loadModel(sourcePath);\n let candidates = pii.detectPiiCandidates(model);\n if (opts.ai) {\n candidates = await pii.verifyWithAi(candidates, {\n completeFn: async (prompt: string) => {\n const r = await ai.complete([{ role: 'user', content: prompt }], {\n feature: 'pii.verify',\n });\n return r.text;\n },\n verifyAtOrBelow: (opts.verifyAtOrBelow ?? 'medium') as 'high' | 'medium' | 'low',\n });\n }\n const fmt = (opts.format ?? 'table').toLowerCase();\n let payload: string;\n if (fmt === 'json') {\n payload = JSON.stringify(candidates, null, 2);\n } else if (fmt === 'markdown') {\n payload = renderMarkdown(candidates);\n } else {\n payload = renderTable(candidates);\n }\n await emit(payload, opts.out);\n },\n );\n\n cmd\n .command('mask')\n .description('Render Unity-Catalog column-mask DDL for detected PII columns.')\n .requiredOption('--source <path>', '.ddtproj or .ddtpac to scan.')\n .option(\n '--unmasked-group <name>',\n \"Group that sees the unmasked value. Default 'pii-readers'.\",\n 'pii-readers',\n )\n .option(\n '--mask-function-schema <fqn>',\n 'Where mask functions live. Default `governance`.',\n 'governance',\n )\n .option('--ai', 'Route low/medium-confidence candidates through the AI verifier first.', false)\n .option('-o, --out <path>', 'Output file path. Default: ./anonymize.sql.')\n .action(\n async (opts: {\n source: string;\n unmaskedGroup?: string;\n maskFunctionSchema?: string;\n ai?: boolean;\n out?: string;\n }) => {\n const sourcePath = String(opts.source);\n const model = await loadModel(sourcePath);\n let candidates = pii.detectPiiCandidates(model);\n if (opts.ai) {\n candidates = await pii.verifyWithAi(candidates, {\n completeFn: async (prompt: string) => {\n const r = await ai.complete([{ role: 'user', content: prompt }], {\n feature: 'pii.mask.verify',\n });\n return r.text;\n },\n });\n }\n if (candidates.length === 0) {\n console.error('No PII columns detected.');\n return;\n }\n const sql = pii.renderAnonymizeScript(candidates, {\n unmaskedGroup: String(opts.unmaskedGroup ?? 'pii-readers'),\n maskFunctionSchema: opts.maskFunctionSchema,\n });\n const outPath = opts.out ? path.resolve(String(opts.out)) : path.resolve('anonymize.sql');\n await fs.mkdir(path.dirname(outPath), { recursive: true });\n await fs.writeFile(outPath, sql, 'utf8');\n console.error(`Wrote ${outPath} (${candidates.length} candidate(s), ${sql.length} bytes).`);\n },\n );\n\n return cmd;\n}\n\nfunction renderTable(cands: readonly pii.PiiCandidate[]): string {\n if (cands.length === 0) return 'No PII candidates detected.\\n';\n const lines: string[] = [];\n const fqnW = Math.max(8, ...cands.map((c) => c.fqn.length));\n const colW = Math.max(8, ...cands.map((c) => c.column.length));\n const catW = Math.max(8, ...cands.map((c) => c.category.length));\n lines.push(\n `${'fqn'.padEnd(fqnW)} ${'column'.padEnd(colW)} ${'category'.padEnd(catW)} confidence reason`,\n );\n lines.push(`${'-'.repeat(fqnW)} ${'-'.repeat(colW)} ${'-'.repeat(catW)} ---------- ------`);\n for (const c of cands) {\n lines.push(\n `${c.fqn.padEnd(fqnW)} ${c.column.padEnd(colW)} ${c.category.padEnd(catW)} ${c.confidence.padEnd(10)} ${c.reason}`,\n );\n }\n return lines.join('\\n');\n}\n\nfunction renderMarkdown(cands: readonly pii.PiiCandidate[]): string {\n if (cands.length === 0) return '_No PII candidates detected._';\n const lines: string[] = [];\n lines.push(`# PII candidates (${cands.length})`);\n lines.push('');\n lines.push('| FQN | Column | Category | Confidence | Reason |');\n lines.push('|---|---|---|---|---|');\n for (const c of cands) {\n lines.push(\n `| \\`${c.fqn}\\` | \\`${c.column}\\` | ${c.category} | ${c.confidence} | ${c.reason} |`,\n );\n }\n return lines.join('\\n');\n}\n\nasync function emit(payload: string, out: unknown): Promise<void> {\n if (out) {\n const p = path.resolve(String(out));\n await fs.mkdir(path.dirname(p), { recursive: true });\n await fs.writeFile(p, payload + (payload.endsWith('\\n') ? '' : '\\n'), 'utf8');\n console.error(`Wrote ${p}.`);\n } else {\n process.stdout.write(payload + (payload.endsWith('\\n') ? '' : '\\n'));\n }\n}\n\nasync function loadModel(sourcePath: string): Promise<DatabricksObject[]> {\n if (sourcePath.endsWith('.ddtpac')) {\n const c = await pac.readPac(sourcePath);\n return c.model;\n }\n const loaded = await loadProject(sourcePath);\n return await parseProjectModel(loaded);\n}\n","/**\n * `ddt bisect <fqn>` — find the commit where a specific object first\n * changed in a git-tracked `.ddtproj` project tree.\n *\n * Algorithm:\n * 1. Resolve the FQN to its canonical project file path via\n * `objectFilePath`.\n * 2. Run `git log --follow --format=%H %s %ad` on that path between\n * `--good`..`--bad` (HEAD by default).\n * 3. Report every commit that touched the file, oldest first; the\n * first row is the \"first-change\" SHA the user wants.\n *\n * Pure git+filesystem — no live target required.\n */\nimport { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport { realpathSync } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { loadProject, objectFilePath } from '@ddt-tools/core';\nimport type { DatabricksObjectType } from '@ddt-tools/core';\n\nconst execFileP = promisify(execFile);\n\nfunction parseFqn(raw: string): { database?: string; schema?: string; name: string } {\n const parts = raw\n .split('.')\n .map((p) => p.replace(/^`(.*)`$/, '$1').trim())\n .filter(Boolean);\n if (parts.length === 3) return { database: parts[0]!, schema: parts[1]!, name: parts[2]! };\n if (parts.length === 2) return { schema: parts[0]!, name: parts[1]! };\n return { name: parts[0] ?? raw };\n}\n\nasync function runGit(cwd: string, args: string[]): Promise<string> {\n const { stdout } = await execFileP('git', args, { cwd, maxBuffer: 16 * 1024 * 1024 });\n return stdout;\n}\n\n/**\n * Canonicalize a path so the two sides of the `path.relative(repoRoot,\n * targetPath)` call below stay in the same form. Without this, a Windows\n * 8.3 short name (`C:\\Users\\RUNNER~1\\...`) on one side and the long name\n * (`...\\runneradmin\\...`) that `git rev-parse --show-toplevel` returns on\n * the other produce an out-of-repo `../../RUNNER~1/...` pathspec that git\n * rejects as \"outside repository\". Also collapses macOS `/var` →\n * `/private/var` symlinks. Falls back to the input if the path is absent.\n */\nfunction canonical(p: string): string {\n try {\n return realpathSync.native(p);\n } catch {\n return p;\n }\n}\n\nexport function bisectCommand(): Command {\n const cmd = new Command('bisect');\n cmd\n .description('Find the commit where a specific FQN first changed in the project tree.')\n .argument('<fqn>', 'Fully-qualified name (catalog.schema.name).')\n .option('-p, --project <path>', 'Path to the .ddtproj file.', '.')\n .option('--object-type <type>', 'Object type. Default: TABLE.', 'TABLE')\n .option('--good <ref>', 'Known-good git ref. Default: project root commit.')\n .option('--bad <ref>', 'Known-bad git ref. Default: HEAD.', 'HEAD')\n .option('--format <fmt>', 'Output: table | json.', 'table')\n .action(async (fqnArg: string, opts) => {\n const fqn = parseFqn(fqnArg);\n const objectType = String(opts.objectType).toUpperCase() as DatabricksObjectType;\n // Resolve project root so the file path is absolute and git-relative.\n const projectPath = path.resolve(String(opts.project));\n let projectRoot: string;\n try {\n const loaded = await loadProject(projectPath);\n projectRoot = loaded.rootDir;\n } catch {\n projectRoot = path.dirname(projectPath);\n }\n projectRoot = canonical(projectRoot);\n\n let targetPath: string;\n try {\n targetPath = objectFilePath(projectRoot, objectType, {\n ...(fqn.database ? { database: fqn.database } : {}),\n ...(fqn.schema ? { schema: fqn.schema } : {}),\n name: fqn.name,\n });\n } catch (err) {\n throw new Error(\n `Could not resolve a file path for ${objectType} ${fqnArg}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n\n // Find repo root so git log paths resolve.\n const repoRoot = canonical(\n (await runGit(projectRoot, ['rev-parse', '--show-toplevel'])).trim(),\n );\n const relPath = path.relative(repoRoot, targetPath).split(path.sep).join('/');\n\n const range = String(\n opts.good ? `${String(opts.good)}..${String(opts.bad)}` : String(opts.bad),\n );\n const logArgs = [\n 'log',\n '--follow',\n '--format=%H%x09%ad%x09%an%x09%s',\n '--date=short',\n range,\n '--',\n relPath,\n ];\n let raw: string;\n try {\n raw = await runGit(repoRoot, logArgs);\n } catch (err) {\n throw new Error(\n `git log failed for ${relPath}: ${err instanceof Error ? err.message : String(err)}. ` +\n `Is the project tracked in git? Does the file exist at the path?`,\n );\n }\n\n const entries = raw\n .split('\\n')\n .filter((l) => l.trim())\n .map((line) => {\n const [sha, date, author, subject] = line.split('\\t');\n return { sha: sha ?? '', date: date ?? '', author: author ?? '', subject: subject ?? '' };\n });\n\n if (opts.format === 'json') {\n console.log(JSON.stringify({ fqn: fqnArg, objectType, path: relPath, entries }, null, 2));\n return;\n }\n\n if (entries.length === 0) {\n console.log(`No commits found for ${objectType} ${fqnArg} (path: ${relPath}).`);\n return;\n }\n\n console.log(`Commits touching ${objectType} ${fqnArg}`);\n console.log(` path: ${relPath}`);\n console.log(` range: ${range}`);\n console.log('');\n console.log(' SHA DATE AUTHOR SUBJECT');\n console.log(\n ' ---------- ---------- ------------------ -----------------------------------',\n );\n for (let i = 0; i < entries.length; i++) {\n const e = entries[i]!;\n const marker = i === entries.length - 1 ? ' ◀ first-change' : '';\n console.log(\n ` ${e.sha.slice(0, 10)} ${e.date} ${e.author.padEnd(18).slice(0, 18)} ${e.subject}${marker}`,\n );\n }\n });\n return cmd;\n}\n","/**\n * `ddt changelog --from <ref> --to <ref>` — auto-generate a\n * Markdown CHANGELOG section from git commits between two refs.\n *\n * Mirrors `sdt changelog`. Parses Conventional Commits, groups by\n * category, emits a release section. Deterministic — no AI.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport { Command } from 'commander';\n\nconst execFileP = promisify(execFile);\n\ninterface Commit {\n sha: string;\n type: string;\n scope: string | undefined;\n subject: string;\n isBreaking: boolean;\n}\n\nconst CATEGORY_ORDER: Array<{ type: string; heading: string }> = [\n { type: 'feat', heading: '✨ Features' },\n { type: 'fix', heading: '🐛 Bug fixes' },\n { type: 'perf', heading: '⚡ Performance' },\n { type: 'refactor', heading: '♻️ Refactoring' },\n { type: 'docs', heading: '📚 Documentation' },\n { type: 'test', heading: '🧪 Tests' },\n { type: 'build', heading: '🔧 Build / CI' },\n { type: 'ci', heading: '🔧 Build / CI' },\n { type: 'chore', heading: '🧹 Chores' },\n { type: 'style', heading: '🎨 Style' },\n];\n\nexport function changelogCommand(): Command {\n const cmd = new Command('changelog');\n cmd\n .description(\n 'Generate a Markdown CHANGELOG section from git commits between two refs (Conventional Commits parser).',\n )\n .option('--from <ref>', 'Starting git ref (exclusive). Default: previous tag.', '')\n .option('--to <ref>', 'Ending git ref (inclusive). Default: HEAD.', 'HEAD')\n .option('--repo <path>', 'Path to the git repository. Default: current directory.', '.')\n .option('--version <name>', 'Version heading for the section. Default: --to ref.')\n .option(\n '--scope <pathspec>',\n 'Restrict to commits touching paths matching this git-pathspec (e.g. `Databricks/packages/cli/**`). Default: all paths.',\n )\n .option('-o, --out <path>', 'Append/write to file. Default: stdout.')\n .option('--append', 'When --out is set, prepend to existing file.', false)\n .option(\n '--manifest-dir <path>',\n 'Directory containing deploy manifests (default: .ddt/history). When set, the changelog appends a \"🚀 Deploys\" addendum: one row per manifest with step-status counts + safety summary. Manifest reads are best-effort — corrupt files are skipped silently.',\n )\n .action(async (opts) => {\n const repo = path.resolve(String(opts.repo));\n const to = String(opts.to);\n let from = String(opts.from);\n if (!from) {\n from = await previousTag(repo, to);\n }\n const commits = await collectCommits(\n repo,\n from,\n to,\n opts.scope ? String(opts.scope) : undefined,\n );\n const grouped = groupByType(commits);\n const version = String(opts.version ?? to);\n const today = new Date().toISOString().slice(0, 10);\n const manifestDir = opts.manifestDir\n ? path.resolve(String(opts.manifestDir))\n : path.join(repo, '.ddt', 'history');\n const deploys = await readDeploySummaries(manifestDir);\n const md = renderMarkdown(version, today, from, to, grouped, deploys);\n\n if (opts.out) {\n const out = path.resolve(String(opts.out));\n let body = md;\n if (opts.append) {\n try {\n const existing = await fs.readFile(out, 'utf8');\n body = `${md}\\n${existing}`;\n } catch {\n // file doesn't exist — write fresh.\n }\n }\n await fs.mkdir(path.dirname(out), { recursive: true });\n await fs.writeFile(out, body, 'utf8');\n console.error(`Wrote ${out} (${commits.length} commit(s)).`);\n } else {\n process.stdout.write(md);\n }\n });\n return cmd;\n}\n\nasync function previousTag(repo: string, ref: string): Promise<string> {\n try {\n const { stdout } = await execFileP('git', ['describe', '--tags', '--abbrev=0', `${ref}^`], {\n cwd: repo,\n });\n return stdout.trim();\n } catch {\n const { stdout } = await execFileP('git', ['rev-list', '--max-parents=0', 'HEAD'], {\n cwd: repo,\n });\n return stdout.trim().split('\\n')[0] ?? '';\n }\n}\n\nasync function collectCommits(\n repo: string,\n from: string,\n to: string,\n scope?: string,\n): Promise<Commit[]> {\n const range = from ? `${from}..${to}` : to;\n const args = ['log', '--no-merges', '--pretty=format:%H%x01%s', range];\n if (scope) {\n args.push('--', scope);\n }\n const { stdout } = await execFileP('git', args, {\n cwd: repo,\n maxBuffer: 64 * 1024 * 1024,\n });\n const lines = stdout.split('\\n').filter(Boolean);\n return lines.map((line) => {\n const [sha, subject] = line.split('\\x01');\n return parseCommit(sha!, subject!);\n });\n}\n\nexport function parseCommit(sha: string, subject: string): Commit {\n const m = subject.match(/^([a-z]+)(\\(([^)]+)\\))?(!)?:\\s*(.+)$/i);\n if (!m) {\n return { sha, type: 'chore', scope: undefined, subject, isBreaking: false };\n }\n const type = m[1]!.toLowerCase();\n const scope = m[3];\n const isBreaking = !!m[4];\n const text = m[5]!.trim();\n return { sha, type, scope, subject: text, isBreaking };\n}\n\nfunction groupByType(commits: Commit[]): Map<string, Commit[]> {\n const out = new Map<string, Commit[]>();\n for (const c of commits) {\n const canonical = CATEGORY_ORDER.find((cat) => cat.type === c.type)?.type ?? 'chore';\n const arr = out.get(canonical) ?? [];\n arr.push(c);\n out.set(canonical, arr);\n }\n return out;\n}\n\nfunction renderMarkdown(\n version: string,\n date: string,\n from: string,\n to: string,\n grouped: Map<string, Commit[]>,\n deploys: DeploySummary[],\n): string {\n const lines: string[] = [];\n lines.push(`## ${version} — ${date}`);\n lines.push('');\n lines.push(`_Range: \\`${from || '(initial)'}\\`..\\`${to}\\`_`);\n lines.push('');\n\n const breaking = [...grouped.values()].flat().filter((c) => c.isBreaking);\n if (breaking.length > 0) {\n lines.push('### ⚠️ BREAKING CHANGES');\n lines.push('');\n for (const c of breaking) {\n lines.push(`- ${formatCommitLine(c)}`);\n }\n lines.push('');\n }\n\n const headingsSeen = new Set<string>();\n for (const { heading } of CATEGORY_ORDER) {\n if (headingsSeen.has(heading)) continue;\n headingsSeen.add(heading);\n const types = CATEGORY_ORDER.filter((c) => c.heading === heading).map((c) => c.type);\n const commits = types.flatMap((t) => grouped.get(t) ?? []);\n if (commits.length === 0) continue;\n lines.push(`### ${heading}`);\n lines.push('');\n for (const c of commits) {\n if (c.isBreaking) continue;\n lines.push(`- ${formatCommitLine(c)}`);\n }\n lines.push('');\n }\n\n if (deploys.length > 0) {\n lines.push('### 🚀 Deploys');\n lines.push('');\n for (const d of deploys) {\n lines.push(`- ${formatDeploySummaryLine(d)}`);\n }\n lines.push('');\n }\n return lines.join('\\n');\n}\n\nfunction formatCommitLine(c: Commit): string {\n const scope = c.scope ? `**${c.scope}**: ` : '';\n return `${scope}${c.subject} (\\`${c.sha.slice(0, 7)}\\`)`;\n}\n\n/** One deploy-manifest summary row for the changelog's 🚀 addendum. */\nexport interface DeploySummary {\n filename: string;\n deployedAt?: string;\n workspaceHost?: string;\n finalState?: string;\n failedStepId?: string | null;\n stepCounts: Record<string, number>;\n totalSteps: number;\n}\n\nasync function readDeploySummaries(dir: string): Promise<DeploySummary[]> {\n let entries: string[];\n try {\n entries = await fs.readdir(dir);\n } catch {\n return [];\n }\n const out: DeploySummary[] = [];\n for (const name of entries.sort()) {\n if (!name.endsWith('.json')) continue;\n try {\n const body = await fs.readFile(path.join(dir, name), 'utf8');\n const parsed = JSON.parse(body) as {\n version?: number;\n deployedAt?: string;\n workspaceHost?: string;\n finalState?: string;\n failedStepId?: string | null;\n steps?: Array<{ status?: string }>;\n };\n if (parsed.version !== 1) continue;\n const steps = Array.isArray(parsed.steps) ? parsed.steps : [];\n const stepCounts: Record<string, number> = {};\n for (const s of steps) {\n const status = typeof s.status === 'string' ? s.status : 'unknown';\n stepCounts[status] = (stepCounts[status] ?? 0) + 1;\n }\n out.push({\n filename: name,\n ...(typeof parsed.deployedAt === 'string' ? { deployedAt: parsed.deployedAt } : {}),\n ...(typeof parsed.workspaceHost === 'string'\n ? { workspaceHost: parsed.workspaceHost }\n : {}),\n ...(typeof parsed.finalState === 'string' ? { finalState: parsed.finalState } : {}),\n failedStepId: parsed.failedStepId ?? null,\n stepCounts,\n totalSteps: steps.length,\n });\n } catch {\n // skip\n }\n }\n return out;\n}\n\nfunction formatDeploySummaryLine(d: DeploySummary): string {\n const parts: string[] = [];\n parts.push(`\\`${d.filename}\\``);\n if (d.deployedAt) parts.push(d.deployedAt);\n if (d.workspaceHost) parts.push(d.workspaceHost);\n const stateGlyph =\n d.finalState === 'clean-success'\n ? '✅'\n : d.finalState === 'clean-skipped'\n ? '⏭️'\n : d.finalState === 'dirty'\n ? '🛑'\n : d.finalState === 'clean-partial'\n ? '⚠️'\n : '·';\n parts.push(`${stateGlyph} ${d.finalState ?? 'unknown'}`);\n parts.push(`${d.totalSteps} step(s)`);\n const statusTags = Object.entries(d.stepCounts)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([s, n]) => `${s}:${n}`)\n .join(', ');\n if (statusTags) parts.push(`(${statusTags})`);\n if (d.failedStepId) parts.push(`failed: ${d.failedStepId}`);\n return parts.join(' · ');\n}\n","/**\n * `ddt replay --manifest <path>` — re-execute a previous deploy's\n * forwardSql against a fresh target.\n *\n * Use cases:\n * - Rebuild a dev/stage workspace from production's manifest history\n * (DDL replay against a clean catalog).\n * - Reproduce a customer's failure by replaying their support-bundle\n * manifest against an internal sandbox.\n *\n * Symmetric to `ddt revert` — same manifest format, same executor, but\n * forward instead of reverse.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport {\n DatabricksExecutor,\n createConnection,\n getProfile,\n type DeployManifest,\n type DeployManifestStep,\n} from '@ddt-tools/core';\n\nasync function discoverManifests(input: string): Promise<string[]> {\n const stat = await fs.stat(input).catch(() => null);\n if (!stat) throw new Error(`Manifest path not found: ${input}`);\n if (stat.isFile()) return [path.resolve(input)];\n // Directory — chronological by manifest deployedAt (filename usually\n // contains the timestamp so a lexical sort works).\n const entries = await fs.readdir(input, { withFileTypes: true });\n const files = entries\n .filter((e) => e.isFile() && e.name.toLowerCase().endsWith('.json'))\n .map((e) => path.join(input, e.name))\n .sort();\n if (files.length === 0) throw new Error(`No .json manifests under ${input}.`);\n return files;\n}\n\nexport function replayCommand(): Command {\n const cmd = new Command('replay');\n cmd\n .description(\n 'Re-execute forwardSql from one or more deploy manifests against a target workspace.',\n )\n .requiredOption('--manifest <path>', 'Path to a manifest .json (or a directory of them).')\n .requiredOption('--connection <name>', 'Connection profile to replay against.')\n .option('--yes', 'Explicit confirmation. Required because replay rebuilds DDL.', false)\n .option('--filter <pattern>', 'Only replay steps whose fqn includes this substring.')\n .option('--from-step <id>', 'Start at this step id (inclusive).')\n .option('--to-step <id>', 'Stop after this step id (inclusive).')\n .option(\n '--continue-on-error',\n 'Continue past failed statements. Default: stop on first failure.',\n false,\n )\n .option('--dry-run', 'Print what would be replayed without executing.', false)\n .action(async (opts) => {\n const manifestPaths = await discoverManifests(String(opts.manifest));\n const manifests: { path: string; manifest: DeployManifest }[] = [];\n for (const p of manifestPaths) {\n const raw = await fs.readFile(p, 'utf8');\n const m = JSON.parse(raw) as DeployManifest;\n if (m.version !== 1) {\n throw new Error(\n `${p}: unsupported manifest version ${m.version} (this CLI understands v1)`,\n );\n }\n manifests.push({ path: p, manifest: m });\n }\n manifests.sort((a, b) => (a.manifest.deployedAt < b.manifest.deployedAt ? -1 : 1));\n\n const profile = await getProfile(String(opts.connection));\n const filter = opts.filter ? String(opts.filter) : '';\n const fromId = opts.fromStep ? String(opts.fromStep) : '';\n const toId = opts.toStep ? String(opts.toStep) : '';\n\n type FlatStep = { step: DeployManifestStep; manifestPath: string; deployedAt: string };\n const flatSteps: FlatStep[] = [];\n let inRange = !fromId;\n for (const { path: p, manifest } of manifests) {\n for (const s of manifest.steps) {\n if (!inRange) {\n if (s.id === fromId) inRange = true;\n else continue;\n }\n if (filter && !s.fqn.includes(filter)) continue;\n if (s.status !== 'SUCCESS' && s.status !== 'ROLLED_BACK') continue;\n flatSteps.push({ step: s, manifestPath: p, deployedAt: manifest.deployedAt });\n if (toId && s.id === toId) {\n inRange = false;\n break;\n }\n }\n }\n\n console.log(\n `Replay plan: ${flatSteps.length} step(s) across ${manifests.length} manifest(s) → ${profile.auth.host}`,\n );\n console.log('');\n\n if (opts.dryRun) {\n for (const { step, deployedAt } of flatSteps) {\n console.log(`▶ ${deployedAt} ${step.objectType} ${step.fqn}`);\n console.log(` ${step.forwardSql.split('\\n')[0]?.slice(0, 100) ?? ''}`);\n }\n console.log('');\n console.log(`Dry-run summary: ${flatSteps.length} step(s) would replay.`);\n return;\n }\n\n if (!opts.yes) {\n throw new Error(\n 'Refusing to replay without --yes. Replay re-executes historical DDL against the target.',\n );\n }\n\n const conn = createConnection(profile);\n let succeeded = 0;\n let failed = 0;\n try {\n await conn.connect();\n const executor = new DatabricksExecutor(conn);\n for (const { step, deployedAt } of flatSteps) {\n process.stdout.write(`▶ ${deployedAt} ${step.objectType} ${step.fqn} …`);\n const t0 = Date.now();\n try {\n await executor.execute(step.forwardSql);\n console.log(` ✓ (${Date.now() - t0}ms)`);\n succeeded++;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.log(` ✗ ${msg}`);\n failed++;\n if (!opts.continueOnError) {\n console.error('');\n console.error('Stopping on first failure. Use --continue-on-error to push through.');\n break;\n }\n }\n }\n } finally {\n await conn.disconnect();\n }\n\n console.log('');\n console.log(`Summary: ${succeeded} replayed, ${failed} failed.`);\n if (failed > 0) process.exitCode = 1;\n });\n return cmd;\n}\n","/**\n * `ddt drift-gate` — multi-region/replica drift gate.\n *\n * Compares the live schema in N replica workspaces against a primary\n * workspace's live schema. Useful for orgs that replicate Unity Catalog\n * state across regions (Delta Sharing, multi-workspace deployments) and\n * want a CI gate that fires the moment any replica drifts from the\n * primary.\n *\n * Algorithm:\n * 1. Extract primary's live model.\n * 2. For each replica, extract live model + compare against primary.\n * 3. Aggregate per-replica diff counts.\n * 4. Exit non-zero if any replica has drift > threshold.\n *\n * Combine with the existing `ddt drift` command (project ↔ region) to\n * cover both vectors: (a) project drift (drift) and (b) inter-region\n * drift (drift-gate).\n */\nimport { Command } from 'commander';\nimport {\n AccountExtractor,\n CompareEngine,\n InMemorySource,\n createConnection,\n defaultExtractors,\n getProfile,\n} from '@ddt-tools/core';\n\ninterface RegionResult {\n profile: string;\n workspaceHost: string;\n added: number;\n removed: number;\n modified: number;\n total: number;\n}\n\nexport function driftGateCommand(): Command {\n const cmd = new Command('drift-gate');\n cmd\n .description(\n 'Refuse-on-drift CI gate across multiple replica workspaces. Compares replicas against a primary.',\n )\n .requiredOption('--primary <profile>', 'Primary workspace connection profile.')\n .requiredOption('--replicas <list>', 'Comma-separated replica connection profile names.')\n .option('--catalog <catalog>', 'Limit drift comparison to a single catalog.')\n .option('--schema <schema>', 'Limit drift comparison to a single schema (requires --catalog).')\n .option(\n '--threshold <n>',\n 'Max allowed differences per replica before the gate fails. Default 0.',\n '0',\n )\n .option('--format <fmt>', 'Output: table | json.', 'table')\n .action(async (opts) => {\n const primary = await getProfile(String(opts.primary));\n const replicaNames = String(opts.replicas)\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean);\n if (replicaNames.length === 0) {\n throw new Error('At least one replica profile is required via --replicas.');\n }\n const threshold = Number.parseInt(String(opts.threshold), 10);\n const scope = {\n ...(opts.catalog ? { catalog: String(opts.catalog) } : {}),\n ...(opts.schema ? { schema: String(opts.schema) } : {}),\n };\n\n // 1. Extract primary.\n const primaryConn = createConnection(primary);\n let primaryObjs;\n try {\n await primaryConn.connect();\n primaryObjs = await new AccountExtractor(defaultExtractors()).extract(primaryConn, scope);\n } finally {\n await primaryConn.disconnect();\n }\n const primarySource = new InMemorySource(primaryObjs, {\n kind: 'live',\n label: `primary:${primary.auth.host}`,\n });\n\n const results: RegionResult[] = [];\n const engine = new CompareEngine();\n\n // 2. Per-replica compare.\n for (const replicaName of replicaNames) {\n const replicaProfile = await getProfile(replicaName);\n const replicaConn = createConnection(replicaProfile);\n let replicaObjs;\n try {\n await replicaConn.connect();\n replicaObjs = await new AccountExtractor(defaultExtractors()).extract(replicaConn, scope);\n } finally {\n await replicaConn.disconnect();\n }\n const replicaSource = new InMemorySource(replicaObjs, {\n kind: 'live',\n label: `replica:${replicaProfile.auth.host}`,\n });\n const result = await engine.compare(primarySource, replicaSource);\n const { added, removed, modified } = result.summary;\n results.push({\n profile: replicaName,\n workspaceHost: replicaProfile.auth.host,\n added,\n removed,\n modified,\n total: added + removed + modified,\n });\n }\n\n if (opts.format === 'json') {\n console.log(\n JSON.stringify({ primary: primary.auth.host, threshold, replicas: results }, null, 2),\n );\n } else {\n console.log(`Drift gate — primary ${primary.auth.host}`);\n console.log('');\n console.log(\n ' REPLICA-PROFILE WORKSPACE-HOST ADD RM MOD TOTAL STATUS',\n );\n console.log(\n ' ---------------------- ------------------------------ --- -- --- ----- ------',\n );\n for (const r of results) {\n const status = r.total > threshold ? 'DRIFT' : 'OK';\n console.log(\n ` ${r.profile.padEnd(22).slice(0, 22)} ${r.workspaceHost.padEnd(30).slice(0, 30)} ${String(r.added).padStart(3)} ${String(r.removed).padStart(2)} ${String(r.modified).padStart(3)} ${String(r.total).padStart(5)} ${status}`,\n );\n }\n }\n\n const drifting = results.filter((r) => r.total > threshold);\n if (drifting.length > 0) {\n console.error('');\n console.error(`Drift detected in ${drifting.length} replica(s) (threshold=${threshold}).`);\n process.exitCode = 1;\n }\n });\n return cmd;\n}\n","/**\n * `ddt promote --from <profile> --to <profile>` — branch-per-env deploy\n * automation.\n *\n * Compares two live workspaces (typically dev → stage or stage → prod),\n * generates the migration script + safety report, and either:\n * - prints the bundle to stdout (default), or\n * - opens a pull request with the diff + safety report attached\n * (`--open-pr` + `--repo`). Requires `gh` (GitHub CLI) on PATH.\n *\n * Stage promotion workflow: when a feature is verified in dev, run\n * `ddt promote --from dev --to stage --open-pr`; the bot generates a\n * \"promote ABC → stage\" PR with the SQL preview + safety findings + AI\n * narration so the reviewer can approve without re-running compare.\n */\nimport { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport { promises as fs } from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport {\n CompareEngine,\n ScriptGenerator,\n InMemorySource,\n AccountExtractor,\n createConnection,\n defaultExtractors,\n getProfile,\n safety,\n diffPromotionEnvConfigs,\n renderEnvConfigDiffMarkdown,\n parsePromotionProfile,\n filterApprovalsByProfile,\n evaluatePromotionGate,\n summarizePromotionPlan,\n type EvaluatePromotionGateInputs,\n type PromotionApprovalState,\n type PromotionEnvironment,\n type PromotionEnvironmentConfig,\n type PromotionGateDecision,\n type PromotionPlanSummary,\n type PromotionProfile,\n} from '@ddt-tools/core';\ntype SafetyAssessment = safety.SafetyAssessment;\n\nconst execFileP = promisify(execFile);\n\nexport function promoteCommand(): Command {\n const cmd = new Command('promote');\n cmd\n .description(\n 'Branch-per-env deploy: compare live source→target, optionally open a PR with the deploy bundle.',\n )\n .option(\n '--from <profile>',\n 'Source environment connection profile (e.g. dev). Required for root action.',\n )\n .option(\n '--to <profile>',\n 'Target environment connection profile (e.g. stage). Required for root action.',\n )\n .option('--catalog <catalog>', 'Limit to a single catalog.')\n .option('--schema <schema>', 'Limit to a single schema (requires --catalog).')\n .option(\n '--from-profile <path>',\n 'Path to source promotion profile JSON (parsed via parsePromotionProfile). ' +\n 'Defaults to `.ddt/profiles/<from>.json` when present. PROMOTE.1+.3 gate wireup.',\n )\n .option(\n '--to-profile <path>',\n 'Path to target promotion profile JSON (parsed via parsePromotionProfile). ' +\n 'Defaults to `.ddt/profiles/<to>.json` when present. PROMOTE.1+.3 gate wireup.',\n )\n .option(\n '--approve <approver>',\n 'Record an approval from <approver> (repeatable). Counts toward target.requiredApprovals; ' +\n 'filtered by approver whitelist if the target profile declares one.',\n collectRepeatable,\n [] as string[],\n )\n .option(\n '--reject <approver>',\n 'Record an explicit rejection from <approver> (repeatable). Any single rejection blocks ' +\n 'regardless of approvals count; filtered by approver whitelist.',\n collectRepeatable,\n [] as string[],\n )\n .option(\n '--force',\n 'Bypass safety-classifier blockers on non-production targets. NEVER bypasses ' +\n 'EXPLICIT_REJECTION; refused outright when target.isProduction is true.',\n false,\n )\n .option(\n '--open-pr',\n 'Open a GitHub PR with the deploy bundle. Requires `gh` CLI + --repo.',\n false,\n )\n .option('--repo <slug>', 'GitHub repo slug (owner/repo) — required with --open-pr.')\n .option('--base <branch>', 'PR base branch. Default: main.', 'main')\n .option('--branch <name>', 'PR head branch name. Default: ddt-promote/<timestamp>.')\n .option('-o, --output <path>', 'Write the deploy bundle to <path> (markdown). Default: stdout.')\n .action(async (opts) => {\n if (!opts.from || !opts.to) {\n throw new Error(\n \"required options '--from <profile>' and '--to <profile>' must be specified\",\n );\n }\n const fromProfile = await getProfile(String(opts.from));\n const toProfile = await getProfile(String(opts.to));\n const scope = {\n ...(opts.catalog ? { catalog: String(opts.catalog) } : {}),\n ...(opts.schema ? { schema: String(opts.schema) } : {}),\n };\n\n // Extract both sides.\n const extract = async (profile: typeof fromProfile, label: string) => {\n const conn = createConnection(profile);\n try {\n await conn.connect();\n const account = new AccountExtractor(defaultExtractors());\n const objs = await account.extract(conn, scope);\n return new InMemorySource(objs, { kind: 'live', label });\n } finally {\n await conn.disconnect();\n }\n };\n const fromSource = await extract(fromProfile, `from:${fromProfile.auth.host}`);\n const toSource = await extract(toProfile, `to:${toProfile.auth.host}`);\n\n // Compare from → to (i.e., apply differences from `from` onto `to`).\n const engine = new CompareEngine();\n const result = await engine.compare(fromSource, toSource);\n\n const totalChanges = result.summary.added + result.summary.removed + result.summary.modified;\n if (totalChanges === 0) {\n console.log(\n `Nothing to promote: ${String(opts.from)} → ${String(opts.to)} is already in sync.`,\n );\n return;\n }\n\n // Generate migration script.\n const generator = new ScriptGenerator();\n const script = generator.generate(result, {});\n const safetyAssessment = safety.assess(result);\n\n const fromPromotionProfile = await loadPromotionProfileForCli(\n opts.fromProfile ? String(opts.fromProfile) : undefined,\n String(opts.from),\n '.ddt',\n '--from-profile',\n );\n const toPromotionProfile = await loadPromotionProfileForCli(\n opts.toProfile ? String(opts.toProfile) : undefined,\n String(opts.to),\n '.ddt',\n '--to-profile',\n );\n\n const gate = evaluatePromoteCliGate({\n from: String(opts.from),\n to: String(opts.to),\n fromProfile: fromPromotionProfile,\n toProfile: toPromotionProfile,\n approvers: parseApproverList(opts.approve),\n rejections: parseRejectionList(opts.reject),\n force: opts.force === true,\n safety: safetyAssessment,\n });\n\n if (!gate.decision.proceed) {\n process.stderr.write(`${gate.summary.headline}\\n`);\n process.stderr.write(renderPromoteGateMarkdown(gate));\n process.exitCode = 1;\n return;\n }\n if (gate.decision.warnings.length > 0) {\n process.stderr.write(`${gate.summary.headline}\\n`);\n for (const w of gate.decision.warnings) {\n process.stderr.write(` warning: ${w.code} — ${w.message}\\n`);\n }\n }\n\n // Build the deploy bundle (markdown).\n const lines: string[] = [];\n lines.push(`# Promote: ${String(opts.from)} → ${String(opts.to)}`);\n lines.push('');\n lines.push(`Generated by \\`ddt promote\\` at ${new Date().toISOString()}.`);\n lines.push('');\n lines.push(renderPromoteGateMarkdown(gate));\n lines.push('## Diff summary');\n lines.push('');\n lines.push(`- **Added**: ${result.summary.added}`);\n lines.push(`- **Removed**: ${result.summary.removed}`);\n lines.push(`- **Modified**: ${result.summary.modified}`);\n lines.push('');\n lines.push('## Safety');\n lines.push('');\n const groups = safety.groupByReversibility(safetyAssessment);\n lines.push(safety.formatReversibilityBuckets(groups));\n lines.push('');\n lines.push('## Migration script');\n lines.push('');\n lines.push('```sql');\n lines.push(script.sql);\n lines.push('```');\n const bundle = lines.join('\\n');\n\n // Emit bundle.\n if (opts.output) {\n await fs.writeFile(String(opts.output), bundle, 'utf8');\n console.log(`Wrote deploy bundle → ${String(opts.output)}`);\n } else if (!opts.openPr) {\n console.log(bundle);\n }\n\n if (opts.openPr) {\n if (!opts.repo) throw new Error('--repo <owner/repo> is required with --open-pr');\n const branchName = String(\n opts.branch ?? `ddt-promote/${String(opts.from)}-to-${String(opts.to)}-${Date.now()}`,\n );\n const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'ddt-promote-'));\n const bodyPath = path.join(tmpDir, 'pr-body.md');\n await fs.writeFile(bodyPath, bundle, 'utf8');\n const totalChanges =\n result.summary.added + result.summary.removed + result.summary.modified;\n const title = `Promote: ${String(opts.from)} → ${String(opts.to)} (${totalChanges} changes)`;\n // Open PR via `gh` — leans on the user's auth + branch creation.\n const args = [\n 'pr',\n 'create',\n '--repo',\n String(opts.repo),\n '--base',\n String(opts.base),\n '--head',\n branchName,\n '--title',\n title,\n '--body-file',\n bodyPath,\n ];\n try {\n const { stdout } = await execFileP('gh', args);\n console.log(stdout.trim());\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(\n `gh pr create failed: ${msg}\\n` +\n `Manual workaround: the bundle is at ${bodyPath}; paste it into a PR by hand.`,\n );\n }\n }\n });\n\n cmd\n .command('diff')\n .description(\n 'Diff two promotion-environment profile JSON files (PROMOTE.2 / PROMOTE.3 wireup). ' +\n 'Pure file I/O — never compares secret values, only secret keys.',\n )\n .requiredOption(\n '--source <path>',\n 'Path to the source .ddt/profiles/<env>.json (parsed via parsePromotionProfile).',\n )\n .requiredOption('--target <path>', 'Path to the target profile JSON.')\n .option('--format <fmt>', 'Output format: markdown (default) | json', 'markdown')\n .action(async (opts: { source: string; target: string; format?: string }) => {\n const format = String(opts.format ?? 'markdown').toLowerCase();\n if (format !== 'markdown' && format !== 'json') {\n process.stderr.write(\n `Invalid --format ${JSON.stringify(opts.format)}; expected \"markdown\" or \"json\".\\n`,\n );\n process.exitCode = 1;\n return;\n }\n\n const sourcePath = path.resolve(String(opts.source));\n const targetPath = path.resolve(String(opts.target));\n const sourceText = await fs.readFile(sourcePath, 'utf8');\n const targetText = await fs.readFile(targetPath, 'utf8');\n\n let sourceJson: unknown;\n let targetJson: unknown;\n try {\n sourceJson = JSON.parse(sourceText);\n } catch (err) {\n emitDiffError(\n format,\n 'PROFILE_PARSE_ERROR',\n `--source is not valid JSON: ${describeErr(err)}`,\n );\n process.exitCode = 1;\n return;\n }\n try {\n targetJson = JSON.parse(targetText);\n } catch (err) {\n emitDiffError(\n format,\n 'PROFILE_PARSE_ERROR',\n `--target is not valid JSON: ${describeErr(err)}`,\n );\n process.exitCode = 1;\n return;\n }\n\n const sourceParse = parsePromotionProfile(sourceJson);\n if (!sourceParse.profile) {\n emitDiffError(format, 'PROFILE_INVALID', renderParseErrors('--source', sourceParse.errors));\n process.exitCode = 2;\n return;\n }\n const targetParse = parsePromotionProfile(targetJson);\n if (!targetParse.profile) {\n emitDiffError(format, 'PROFILE_INVALID', renderParseErrors('--target', targetParse.errors));\n process.exitCode = 2;\n return;\n }\n\n const source = profileToEnvConfig(sourceParse.profile);\n const target = profileToEnvConfig(targetParse.profile);\n const diff = diffPromotionEnvConfigs(source, target);\n\n if (format === 'json') {\n process.stdout.write(JSON.stringify(diff, null, 2) + '\\n');\n } else {\n const md = renderEnvConfigDiffMarkdown(diff);\n process.stdout.write(md);\n if (!md.endsWith('\\n')) process.stdout.write('\\n');\n }\n });\n\n return cmd;\n}\n\nfunction profileToEnvConfig(profile: PromotionProfile): PromotionEnvironmentConfig {\n return {\n name: profile.name,\n profileName: profile.profileName,\n isProduction: profile.isProduction,\n requiredApprovals: profile.requiredApprovals,\n ...(profile.variables ? { variables: profile.variables } : {}),\n ...(profile.secretKeys ? { secretKeys: profile.secretKeys } : {}),\n ...(profile.profileFields ? { profileFields: profile.profileFields } : {}),\n };\n}\n\nfunction describeErr(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\nfunction renderParseErrors(\n label: string,\n errors: readonly { path: string; message: string }[],\n): string {\n const lines = errors.map((e) => ` - ${e.path}: ${e.message}`);\n return `${label} failed parsePromotionProfile:\\n${lines.join('\\n')}`;\n}\n\nfunction emitDiffError(format: string, errorCode: string, message: string): void {\n if (format === 'json') {\n process.stdout.write(JSON.stringify({ ok: false, errorCode, message }) + '\\n');\n } else {\n process.stderr.write(`promote diff refused: ${errorCode}\\n${message}\\n`);\n }\n}\n\nfunction collectRepeatable(value: string, prev: string[]): string[] {\n return [...prev, value];\n}\n\nexport function parseApproverList(raw: unknown): string[] {\n if (!Array.isArray(raw)) return [];\n const out: string[] = [];\n for (const v of raw) {\n if (typeof v === 'string' && v.length > 0) out.push(v);\n }\n return out;\n}\n\nexport interface PromoteCliRejection {\n readonly approver: string;\n readonly reason?: string;\n}\n\nexport function parseRejectionList(raw: unknown): PromoteCliRejection[] {\n if (!Array.isArray(raw)) return [];\n const out: PromoteCliRejection[] = [];\n for (const v of raw) {\n if (typeof v !== 'string' || v.length === 0) continue;\n out.push({ approver: v });\n }\n return out;\n}\n\n/**\n * PROMOTE.1 + PROMOTE.3 gate inputs for the CLI orchestrator. Pure data\n * — file I/O happens in the caller, this helper composes the substrate.\n */\nexport interface PromoteCliGateOptions {\n readonly from: string;\n readonly to: string;\n readonly fromProfile?: PromotionProfile;\n readonly toProfile?: PromotionProfile;\n readonly approvers: readonly string[];\n readonly rejections: readonly PromoteCliRejection[];\n readonly force: boolean;\n readonly safety: SafetyAssessment;\n readonly now?: string;\n}\n\nexport interface PromoteCliGateOutcome {\n readonly decision: PromotionGateDecision;\n readonly summary: PromotionPlanSummary;\n readonly source: PromotionEnvironment;\n readonly target: PromotionEnvironment;\n}\n\nfunction profileToEnvironment(\n name: string,\n profile: PromotionProfile | undefined,\n): PromotionEnvironment {\n if (profile) {\n return {\n name: profile.name,\n profileName: profile.profileName,\n isProduction: profile.isProduction,\n requiredApprovals: profile.requiredApprovals,\n };\n }\n return { name, profileName: name, isProduction: false, requiredApprovals: 0 };\n}\n\n/**\n * Pure composition of parsePromotionProfile + filterApprovalsByProfile +\n * evaluatePromotionGate + summarizePromotionPlan. Unit-testable without\n * a live warehouse connection — pin tests cover production --force\n * refusal, EXPLICIT_REJECTION via --reject, INSUFFICIENT_APPROVALS,\n * approver-whitelist filtering, and warnings-only success.\n */\nexport function evaluatePromoteCliGate(opts: PromoteCliGateOptions): PromoteCliGateOutcome {\n const now = opts.now ?? new Date().toISOString();\n const source = profileToEnvironment(opts.from, opts.fromProfile);\n const target = profileToEnvironment(opts.to, opts.toProfile);\n const approvals = opts.approvers.map((approver) => ({ approver, at: now }));\n const rejections = opts.rejections.map((r) => ({\n approver: r.approver,\n at: now,\n ...(r.reason !== undefined ? { reason: r.reason } : {}),\n }));\n let approvalState: PromotionApprovalState = { approvals, rejections };\n if (opts.toProfile) {\n approvalState = filterApprovalsByProfile(opts.toProfile, approvalState);\n }\n const inputs: EvaluatePromotionGateInputs = {\n source,\n target,\n safety: opts.safety,\n approvalState,\n force: opts.force,\n };\n const decision = evaluatePromotionGate(inputs);\n const summary = summarizePromotionPlan(inputs);\n return { decision, summary, source, target };\n}\n\n/** Markdown rendering of a promotion-gate outcome — embedded in the\n * deploy bundle (so the PR body carries the decision) and printed to\n * stderr on refusal. */\nexport function renderPromoteGateMarkdown(outcome: PromoteCliGateOutcome): string {\n const lines: string[] = [];\n lines.push('## Promotion gate');\n lines.push('');\n lines.push(`**${outcome.summary.headline}**`);\n lines.push('');\n lines.push(\n `- **Source**: ${outcome.source.name} (profile \\`${outcome.source.profileName}\\`${outcome.source.isProduction ? ', production' : ''})`,\n );\n lines.push(\n `- **Target**: ${outcome.target.name} (profile \\`${outcome.target.profileName}\\`${outcome.target.isProduction ? ', production' : ''})`,\n );\n lines.push(\n `- **Approvals**: ${outcome.summary.approvalsRecorded} recorded / ${outcome.summary.approvalsRequired} required`,\n );\n lines.push('');\n if (outcome.decision.blockers.length > 0) {\n lines.push(`### Blockers (${outcome.decision.blockers.length})`);\n lines.push('');\n for (const b of outcome.decision.blockers) {\n lines.push(`- **${b.code}** — ${b.message}`);\n }\n lines.push('');\n }\n if (outcome.decision.warnings.length > 0) {\n lines.push(`### Warnings (${outcome.decision.warnings.length})`);\n lines.push('');\n for (const w of outcome.decision.warnings) {\n lines.push(`- **${w.code}** — ${w.message}`);\n }\n lines.push('');\n }\n return lines.join('\\n');\n}\n\n/**\n * Load a promotion profile from disk for the CLI gate. Behavior:\n * - If `explicitPath` is set, the file MUST exist + parse cleanly.\n * Missing / malformed → throws with a precise error.\n * - If `explicitPath` is undefined, tries the default well-known path\n * `<configDir>/profiles/<envName>.json`. Missing file → returns\n * `undefined` silently (no profile mode, gate runs with defaults).\n * Malformed → throws (so a typo is not silently ignored).\n */\nexport async function loadPromotionProfileForCli(\n explicitPath: string | undefined,\n envName: string,\n configDir: string,\n flagName: string,\n): Promise<PromotionProfile | undefined> {\n const targetPath = explicitPath\n ? path.resolve(explicitPath)\n : path.resolve(path.join(configDir, 'profiles', `${envName}.json`));\n let text: string;\n try {\n text = await fs.readFile(targetPath, 'utf8');\n } catch (err) {\n if (explicitPath !== undefined) {\n throw new Error(`${flagName} ${targetPath} could not be read: ${describeErr(err)}`);\n }\n return undefined; // silent fallback for default well-known path\n }\n let json: unknown;\n try {\n json = JSON.parse(text);\n } catch (err) {\n throw new Error(`${targetPath} is not valid JSON: ${describeErr(err)}`);\n }\n const parsed = parsePromotionProfile(json);\n if (!parsed.profile) {\n throw new Error(renderParseErrors(targetPath, parsed.errors));\n }\n return parsed.profile;\n}\n","/**\n * `ddt data-fit --source <pac> --target <pac>` — pre-flight data-fit\n * probe queries for narrowing type changes.\n *\n * Mirrors `Snowflake/packages/cli/src/commands/data-fit.ts`. Walks the\n * source-vs-target compare, finds every table-like object whose\n * column-level diff includes a type change, classifies each change\n * via `@ddt-tools/core/types.classifyTypeChange`, and for every\n * `data-fit-required` verdict emits a `SELECT count_if(...)` probe via\n * `dataFitProbeSql`. The probe queries are read-only — run them before\n * `ddt publish --apply` to confirm zero rows overflow the new type.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { CompareEngine, PacSource, types, type DatabricksObject } from '@ddt-tools/core';\n\ninterface ColumnWithType {\n name: string;\n dataType: unknown;\n}\n\nfunction getColumns(obj: DatabricksObject): ColumnWithType[] | undefined {\n if (!('columns' in obj)) return undefined;\n const cols = (obj as { columns?: unknown }).columns;\n if (!Array.isArray(cols)) return undefined;\n // DDT columns store the type under `.type`; normalize so the shared\n // ColumnWithType reader can find it under `.dataType` like the SDT\n // mirror. Defensive: keep `.dataType` if a producer happens to pass\n // SDT-shaped objects through this CLI.\n return (cols as { name: string; type?: unknown; dataType?: unknown }[]).map((c) => ({\n name: c.name,\n dataType: c.dataType ?? c.type,\n }));\n}\n\nfunction dataTypeToString(dt: unknown): string {\n if (typeof dt === 'string') return dt;\n if (dt && typeof dt === 'object') {\n const d = dt as {\n base?: string;\n precision?: number;\n scale?: number;\n length?: number;\n raw?: string;\n };\n if (d.raw) return d.raw;\n if (!d.base) return JSON.stringify(dt);\n if (d.precision !== undefined && d.scale !== undefined) {\n return `${d.base}(${d.precision},${d.scale})`;\n }\n if (d.length !== undefined) return `${d.base}(${d.length})`;\n return d.base;\n }\n return String(dt ?? '');\n}\n\nfunction backtickFqn(obj: DatabricksObject): string {\n const fqn = (obj as { fqn?: { database?: string; schema?: string; name: string } }).fqn;\n if (!fqn) return '<unknown>';\n return [fqn.database, fqn.schema, fqn.name]\n .filter(Boolean)\n .map((p) => `\\`${p}\\``)\n .join('.');\n}\n\nfunction backtickCol(name: string): string {\n return `\\`${name}\\``;\n}\n\nexport function dataFitCommand(): Command {\n const cmd = new Command('data-fit');\n cmd\n .description(\n 'Emit pre-flight SELECT count_if() probes for every narrowing type change in a pac↔pac compare. Run them against the live target before --apply.',\n )\n .requiredOption('--source <path>', '.ddtpac with the desired state.')\n .requiredOption('--target <path>', '.ddtpac with the current state.')\n .option('-o, --out <path>', 'Output SQL file. Default: stdout.')\n .option('--format <fmt>', 'Output format: sql | json. Default: sql.', 'sql')\n .action(async (opts) => {\n const source = new PacSource(path.resolve(String(opts.source)));\n const target = new PacSource(path.resolve(String(opts.target)));\n const engine = new CompareEngine();\n const result = await engine.compare(source, target);\n\n interface Probe {\n fqn: string;\n column: string;\n from: string;\n to: string;\n reason: string;\n sql: string;\n }\n const probes: Probe[] = [];\n\n for (const obj of result.objects) {\n if (obj.kind !== 'modified' || !obj.source || !obj.target) continue;\n const srcCols = getColumns(obj.source);\n const tgtCols = getColumns(obj.target);\n if (!srcCols || !tgtCols) continue;\n const byName = new Map<string, { source: ColumnWithType; target: ColumnWithType }>();\n for (const c of srcCols) byName.set(c.name.toUpperCase(), { source: c, target: c });\n for (const c of tgtCols) {\n const slot = byName.get(c.name.toUpperCase());\n if (slot) slot.target = c;\n }\n for (const [, pair] of byName) {\n if (pair.source === pair.target) continue;\n const fromStr = dataTypeToString(pair.target.dataType);\n const toStr = dataTypeToString(pair.source.dataType);\n if (fromStr === toStr) continue;\n const check = types.classifyTypeChange(fromStr, toStr);\n if (check.verdict !== 'data-fit-required') continue;\n const fqn = backtickFqn(obj.source);\n const colName = pair.source.name;\n const probeSql = types.dataFitProbeSql(check, fqn, backtickCol(colName));\n if (!probeSql) continue;\n probes.push({\n fqn,\n column: colName,\n from: fromStr,\n to: toStr,\n reason: check.reason,\n sql: probeSql,\n });\n }\n }\n\n if (opts.format === 'json') {\n const out = JSON.stringify({ probeCount: probes.length, probes }, null, 2);\n await emit(out, opts.out);\n } else {\n const lines: string[] = [];\n lines.push(`-- Generated by \\`ddt data-fit\\` at ${new Date().toISOString()}.`);\n lines.push(`-- ${probes.length} narrowing type change(s) need a pre-flight check.`);\n lines.push(`-- Run each query against the target; WOULD_FAIL must be 0 before --apply.`);\n lines.push('');\n for (const p of probes) {\n lines.push(`-- PROBE: ${p.fqn}.${backtickCol(p.column)} (${p.from} → ${p.to})`);\n lines.push(`-- Reason: ${p.reason}`);\n lines.push(`${p.sql};`);\n lines.push('');\n }\n if (probes.length === 0) {\n lines.push(\n '-- No narrowing type changes detected. Compare result has only safe or destructive changes;',\n );\n lines.push('-- data-fit probes do not apply.');\n }\n await emit(lines.join('\\n'), opts.out);\n }\n\n if (probes.length === 0) {\n console.error('No narrowing type changes detected — nothing to probe.');\n } else {\n console.error(\n `Generated ${probes.length} data-fit probe(s). Run each against the target and confirm WOULD_FAIL = 0 before \\`ddt publish --apply\\`.`,\n );\n }\n });\n return cmd;\n}\n\nasync function emit(text: string, out: unknown): Promise<void> {\n if (out) {\n const p = path.resolve(String(out));\n await fs.mkdir(path.dirname(p), { recursive: true });\n await fs.writeFile(p, text + (text.endsWith('\\n') ? '' : '\\n'), 'utf8');\n console.error(`Wrote ${p}.`);\n } else {\n process.stdout.write(text + (text.endsWith('\\n') ? '' : '\\n'));\n }\n}\n","/**\n * `ddt data-compare` — Tier-1 SSDT-gap row-level data compare.\n *\n * Reads source + target rows from either:\n * - JSON files (`--source` / `--target`), or\n * - live warehouses (`--source-live <profile>` / `--target-live <profile>`)\n * via `DatabricksConnection.executeRows`.\n *\n * Live mode runs `SELECT <columns> FROM <fqn>` against each side and\n * pipes rows through the dialect-aware `dataCompare.diffRows` substrate.\n *\n * Usage (JSON):\n * ddt data-compare --table CAT.SCH.T --key ID \\\n * --source rows-source.json --target rows-target.json\n *\n * Usage (live):\n * ddt data-compare --table CAT.SCH.T --key ID \\\n * --source-live dev --target-live prod \\\n * [--columns ID,EMAIL,STATUS] [--row-limit 50000]\n *\n * Mirrors `sdt data-compare`.\n */\nimport { promises as fs } from 'fs';\nimport path from 'path';\nimport { Command } from 'commander';\nimport { dataCompare, createConnection, getProfile } from '@ddt-tools/core';\n\nexport function dataCompareCommand(): Command {\n const cmd = new Command('data-compare');\n cmd\n .description(\n 'Row-level data compare: diff two tables by primary key and emit an INSERT/UPDATE/DELETE script ' +\n 'that converts target into source. Source/target rows read from JSON files in v1.',\n )\n .requiredOption(\n '--table <fqn>',\n 'Fully-qualified table name to embed in the emitted script (CATALOG.SCHEMA.TABLE).',\n )\n .requiredOption('--key <cols>', 'Comma-separated primary-key columns.')\n .option(\n '--source <path>',\n 'JSON file containing the source-side rows (TableRow[]). Mutually exclusive with --source-live.',\n )\n .option(\n '--target <path>',\n 'JSON file containing the target-side rows (TableRow[]). Mutually exclusive with --target-live.',\n )\n .option(\n '--source-live <profile>',\n 'Connection profile to read source rows from live via SELECT * FROM --table. Mutually exclusive with --source.',\n )\n .option(\n '--target-live <profile>',\n 'Connection profile to read target rows from live via SELECT * FROM --table. Mutually exclusive with --target.',\n )\n .option(\n '--row-limit <n>',\n 'Cap rows fetched per side in live mode. Default 100000. Use 0 for unbounded (DANGER on prod tables).',\n '100000',\n )\n .option(\n '--columns <cols>',\n 'Comma-separated column list to consider. Defaults to all keys seen in the rows.',\n )\n .option(\n '--max-changes <n>',\n 'Cap the changed-row count (added/removed are not capped). Default 10000.',\n '10000',\n )\n .option(\n '--case-sensitive',\n 'Compare column names case-sensitively (default: false — UC default folding).',\n false,\n )\n .option('--no-transaction', 'Omit BEGIN/COMMIT wrappers from the emitted script.')\n .option('--no-header', 'Omit the REVIEW header from the emitted script.')\n .option('--format <fmt>', 'Output format: sql | json. Default sql.', 'sql')\n .option('-o, --output <path>', 'Write output to a file instead of stdout.')\n .action(async (opts) => {\n await runDataCompare(opts, 'databricks');\n });\n return cmd;\n}\n\nexport async function runDataCompare(\n opts: Record<string, unknown>,\n dialect: 'snowflake' | 'databricks',\n): Promise<void> {\n const fqn = String(opts.table);\n const keyColumns = String(opts.key)\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean);\n if (keyColumns.length === 0) {\n throw new Error('--key must include at least one column.');\n }\n const columns = opts.columns\n ? String(opts.columns)\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean)\n : undefined;\n\n const sourceJson = opts.source as string | undefined;\n const targetJson = opts.target as string | undefined;\n const sourceLive = opts.sourceLive as string | undefined;\n const targetLive = opts.targetLive as string | undefined;\n if (Boolean(sourceJson) === Boolean(sourceLive)) {\n throw new Error('Specify exactly one of --source or --source-live.');\n }\n if (Boolean(targetJson) === Boolean(targetLive)) {\n throw new Error('Specify exactly one of --target or --target-live.');\n }\n const rowLimit = Number(opts.rowLimit ?? '100000');\n\n const [sourceRows, targetRows] = await Promise.all([\n sourceLive\n ? fetchLiveRows(sourceLive, fqn, columns, rowLimit, 'source')\n : readRowsFile(String(sourceJson)),\n targetLive\n ? fetchLiveRows(targetLive, fqn, columns, rowLimit, 'target')\n : readRowsFile(String(targetJson)),\n ]);\n\n const result = dataCompare.diffRows(\n {\n fqn,\n keyColumns,\n ...(columns ? { columns } : {}),\n sourceRows,\n targetRows,\n },\n {\n maxChanges: Number(opts.maxChanges ?? '10000') || 10_000,\n caseSensitiveColumns: opts.caseSensitive === true,\n },\n );\n\n const format = String(opts.format).toLowerCase();\n const out =\n format === 'json'\n ? JSON.stringify(result, null, 2)\n : dataCompare.renderDataCompareScript(result, dialect, {\n transactional: opts.transaction !== false,\n includeHeader: opts.header !== false,\n });\n\n if (opts.output) {\n const outPath = path.resolve(String(opts.output));\n await fs.writeFile(outPath, out, 'utf8');\n console.error(\n `data-compare: wrote ${outPath} (added=${result.diff.added.length} ` +\n `removed=${result.diff.removed.length} changed=${result.diff.changed.length} ` +\n `unchanged=${result.diff.unchanged}${result.truncated ? ' truncated' : ''})`,\n );\n } else {\n process.stdout.write(out);\n if (format !== 'json') process.stdout.write('\\n');\n }\n}\n\nasync function readRowsFile(p: string): Promise<dataCompare.TableRow[]> {\n const raw = await fs.readFile(path.resolve(p), 'utf8');\n const parsed = JSON.parse(raw) as unknown;\n if (!Array.isArray(parsed)) {\n throw new Error(`${p}: expected a JSON array of row objects.`);\n }\n return parsed as dataCompare.TableRow[];\n}\n\nasync function fetchLiveRows(\n profileName: string,\n fqn: string,\n columns: readonly string[] | undefined,\n rowLimit: number,\n side: 'source' | 'target',\n): Promise<dataCompare.TableRow[]> {\n const projection = columns && columns.length > 0 ? columns.join(', ') : '*';\n const limit = rowLimit > 0 ? ` LIMIT ${Math.floor(rowLimit)}` : '';\n const sql = `SELECT ${projection} FROM ${fqn}${limit}`;\n const profile = await getProfile(profileName);\n const conn = createConnection(profile);\n console.error(`data-compare (${side}): connecting to ${profile.auth.host}…`);\n await conn.connect();\n try {\n const rows = await conn.executeRows(sql);\n console.error(\n `data-compare (${side}): fetched ${rows.length} row(s) from ${fqn}${rowLimit > 0 && rows.length === rowLimit ? ' (LIMIT reached — increase --row-limit if more rows are needed)' : ''}.`,\n );\n return rows as dataCompare.TableRow[];\n } finally {\n await conn.disconnect().catch(() => undefined);\n }\n}\n","/**\n * `ddt approval` — manage multi-approver gate tokens (Team-tier).\n *\n * ddt approval add <deploy-id> --as <approver> [--message <text>] [--digest <hex>]\n * ddt approval list <deploy-id>\n * ddt approval clear <deploy-id>\n * ddt approval check <deploy-id> --required N --allowed <ids>\n *\n * Tokens default to `.ddt/approvals/` under the current working\n * directory; override with `--root <path>` on every subcommand.\n *\n * Mirrors `sdt approval`.\n */\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { approval } from '@ddt-tools/core';\n\nconst DEFAULT_ROOT = path.join('.ddt', 'approvals');\n\nexport function approvalCommand(): Command {\n const cmd = new Command('approval');\n cmd.description('Record / list / verify multi-approver gate tokens for prod deploys.');\n\n cmd\n .command('add')\n .description('Record an approval for a deploy id.')\n .argument('<deploy-id>', 'Stable deploy identifier (slug; sanitised in filenames).')\n .requiredOption('--as <approver>', 'Approver identifier (email, username, OIDC subject).')\n .option('--message <text>', 'Optional approval message.')\n .option('--digest <hex>', 'Optional compare/safety digest the approver reviewed.')\n .option('--root <path>', 'Approvals directory.', DEFAULT_ROOT)\n .action(async (deployId: string, opts: Record<string, unknown>) => {\n const record: approval.ApprovalRecord = {\n approver: String(opts.as),\n signedAt: new Date().toISOString(),\n ...(opts.message ? { message: String(opts.message) } : {}),\n ...(opts.digest ? { digest: String(opts.digest) } : {}),\n };\n const file = await approval.appendApproval(String(opts.root), deployId, record);\n console.log(\n `Recorded approval from ${record.approver} for ${deployId} ` +\n `(${file.approvals.length} total).`,\n );\n });\n\n cmd\n .command('list')\n .description('List approvals recorded for a deploy id.')\n .argument('<deploy-id>')\n .option('--root <path>', 'Approvals directory.', DEFAULT_ROOT)\n .option('--json', 'Emit JSON.', false)\n .action(async (deployId: string, opts: Record<string, unknown>) => {\n const file = await approval.readApprovalFile(String(opts.root), deployId);\n if (opts.json) {\n console.log(JSON.stringify(file, null, 2));\n return;\n }\n if (file.approvals.length === 0) {\n console.log(`No approvals recorded for \"${deployId}\".`);\n return;\n }\n console.log(`Approvals for ${deployId}:`);\n for (const a of file.approvals) {\n const meta = [a.signedAt];\n if (a.digest) meta.push(`digest=${a.digest}`);\n if (a.message) meta.push(`message=${JSON.stringify(a.message)}`);\n console.log(` - ${a.approver} (${meta.join('; ')})`);\n }\n });\n\n cmd\n .command('clear')\n .description('Remove all approvals for a deploy id.')\n .argument('<deploy-id>')\n .option('--root <path>', 'Approvals directory.', DEFAULT_ROOT)\n .action(async (deployId: string, opts: Record<string, unknown>) => {\n await approval.clearApprovals(String(opts.root), deployId);\n console.log(`Cleared approvals for ${deployId}.`);\n });\n\n cmd\n .command('check')\n .description('Evaluate the gate. Exits 0 when satisfied, 2 when blocked.')\n .argument('<deploy-id>')\n .requiredOption('--required <n>', 'Number of distinct approvals required.', '2')\n .option('--allowed <ids>', 'Comma-separated allow-list of approvers (empty = any).')\n .option('--digest <hex>', 'Current compare/safety digest; rejects stale approvals.')\n .option('--root <path>', 'Approvals directory.', DEFAULT_ROOT)\n .option('--json', 'Emit JSON.', false)\n .action(async (deployId: string, opts: Record<string, unknown>) => {\n const allowedApprovers = opts.allowed\n ? String(opts.allowed)\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean)\n : [];\n const file = await approval.readApprovalFile(String(opts.root), deployId);\n const outcome = approval.evaluateApprovalGate(\n {\n deployId,\n required: Number(opts.required ?? '2') || 0,\n allowedApprovers,\n ...(opts.digest ? { currentDigest: String(opts.digest) } : {}),\n },\n file.approvals,\n );\n if (opts.json) {\n console.log(JSON.stringify(outcome, null, 2));\n } else if (outcome.satisfied) {\n console.log(\n `OK: ${outcome.satisfiedBy.length} approval(s) — ${outcome.satisfiedBy.join(', ')}.`,\n );\n } else {\n console.error(`BLOCKED: ${outcome.blockReason ?? 'approval gate not satisfied'}.`);\n }\n if (!outcome.satisfied) process.exitCode = 2;\n });\n\n return cmd;\n}\n","/**\n * `ddt advise-tests` — AI-assisted regression-test recommender\n * (Testing Infrastructure Phase 4).\n *\n * Walks a list of changed files (typically the output of\n * `git diff --name-only base..head`), runs a pre-AI heuristic against\n * `@ddt-tools/core/features.DDT_FEATURE_CATALOG`, and asks the configured AI\n * provider to recommend a minimal regression-test set.\n *\n * Mirrors `sdt advise-tests`.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { ai, regressionAdvisor } from '@ddt-tools/core';\n\nexport function adviseTestsCommand(): Command {\n const cmd = new Command('advise-tests');\n cmd\n .description(\n 'PR-time AI regression-test advisor. Walks the DDT feature catalog, flags features whose surfaces match the changed files, ' +\n 'and recommends 1–8 tests to add alongside the diff.',\n )\n .option(\n '--changed-files <path>',\n 'File containing one changed-file path per line. Defaults to reading from stdin when not provided.',\n )\n .option(\n '--diff-summary <text>',\n 'Optional prose summary of the diff. Use \"-\" to read from stdin.',\n )\n .option(\n '--existing-tests <path>',\n 'File listing existing test file paths so the advisor avoids duplicates.',\n )\n .option('--format <fmt>', 'Output format: markdown | json. Default markdown.', 'markdown')\n .option('-o, --out <path>', 'Output file path. Defaults to stdout.')\n .option(\n '--ai-max-spend <usd>',\n \"Refuse the AI call if today's estimated spend ≥ this (USD). 0 = no cap.\",\n '0',\n )\n .action(async (opts) => {\n await runAdviseTests(opts, 'ddt');\n });\n return cmd;\n}\n\nexport async function runAdviseTests(\n opts: Record<string, unknown>,\n toolName: 'ddt' | 'ddt',\n): Promise<void> {\n const changedFiles = opts.changedFiles\n ? splitLines(await fs.readFile(path.resolve(String(opts.changedFiles)), 'utf8'))\n : splitLines(await readStdin());\n if (changedFiles.length === 0) {\n throw new Error(\n 'advise-tests: no changed files supplied. Pass --changed-files or pipe via stdin.',\n );\n }\n const diffSummary =\n opts.diffSummary === '-'\n ? await readStdin()\n : opts.diffSummary\n ? String(opts.diffSummary)\n : undefined;\n const existingTestFiles = opts.existingTests\n ? splitLines(await fs.readFile(path.resolve(String(opts.existingTests)), 'utf8'))\n : undefined;\n\n const result = await regressionAdvisor.adviseTests(\n {\n changedFiles,\n ...(diffSummary ? { diffSummary } : {}),\n ...(existingTestFiles ? { existingTestFiles } : {}),\n },\n {\n completeFn: async (user, system) => {\n const r = await ai.complete(\n [\n { role: 'system', content: system },\n { role: 'user', content: user },\n ],\n {\n feature: 'advise-tests',\n maxSpendUsd: Number(opts.aiMaxSpend ?? '0') || 0,\n },\n );\n return r.text;\n },\n },\n toolName,\n );\n\n const format = String(opts.format ?? 'markdown').toLowerCase();\n const payload =\n format === 'json'\n ? JSON.stringify({ ...result, rawModelText: undefined }, null, 2)\n : regressionAdvisor.renderAdvisorMarkdown(result, toolName);\n\n if (opts.out) {\n const outPath = path.resolve(String(opts.out));\n await fs.mkdir(path.dirname(outPath), { recursive: true });\n await fs.writeFile(outPath, payload + (payload.endsWith('\\n') ? '' : '\\n'), 'utf8');\n console.error(`Wrote ${outPath} (${payload.length} bytes).`);\n } else {\n process.stdout.write(payload + (payload.endsWith('\\n') ? '' : '\\n'));\n }\n}\n\nfunction splitLines(s: string): string[] {\n return s\n .split(/\\r?\\n/)\n .map((l) => l.trim())\n .filter((l) => l.length > 0 && !l.startsWith('#'));\n}\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : (chunk as Buffer));\n }\n return Buffer.concat(chunks).toString('utf8');\n}\n","/**\n * `ddt safer-alternative` — call the AI provider to suggest a safer DDL\n * alternative for a flagged-as-dangerous migration step.\n *\n * Composes `@ddt-tools/core/saferAlternative.suggestSaferAlternative` with the\n * configured AI provider (`@ddt-tools/core/ai.complete`). The CLI is the thin\n * adapter; all the prompt-building and parsing lives in core so the\n * VS Code CodeLens / MCP server / future hosts share the same behavior.\n *\n * Inputs (all surfaced as flags):\n * --code SafetyFindingCode (e.g. COLUMN_DROP, DROP_UNRECOVERABLE)\n * --fqn Object FQN the finding refers to\n * --object-type Object type (e.g. MANAGED_TABLE, VIEW)\n * --reason Short reason from the safety classifier\n * --gate Optional SafetyGate (preserved on the suggestion)\n * --sql <path> Path to a file with the dangerous DDL (or \"-\" for stdin)\n * --context <path> Optional path to the surrounding source DDL\n * --intent <text> Optional human-authored intent notes\n * --format text | json (default text)\n */\nimport { promises as fs } from 'node:fs';\nimport { Command } from 'commander';\nimport { ai, saferAlternative, type safety } from '@ddt-tools/core';\n\nexport function saferAlternativeCommand(): Command {\n const cmd = new Command('safer-alternative');\n cmd\n .description(\n 'AI-assist: propose a safer DDL alternative for a safety finding. Requires a configured AI provider (ddt ai status).',\n )\n .requiredOption('--code <code>', 'SafetyFindingCode (e.g. COLUMN_DROP, DROP_UNRECOVERABLE).')\n .requiredOption('--fqn <fqn>', 'Object FQN the finding refers to.')\n .requiredOption('--object-type <type>', 'Object type (e.g. MANAGED_TABLE, VIEW, FUNCTION).')\n .requiredOption('--reason <text>', 'Short reason text from the safety classifier.')\n .option(\n '--gate <gate>',\n 'Optional SafetyGate the finding raised (e.g. REQUIRE_ALLOW_DROP_COLUMN).',\n )\n .option('--sql <path>', 'Path to a file with the dangerous DDL. Use \"-\" to read from stdin.')\n .option('--context <path>', 'Optional path to the surrounding source DDL.')\n .option('--intent <text>', 'Optional human-authored intent notes.')\n .option('--format <fmt>', 'Output format: text | json. Default text.', 'text')\n .option(\n '--ai-max-spend <usd>',\n \"Refuse the call if today's estimated spend ≥ this (USD). 0 = no cap.\",\n '0',\n )\n .action(async (opts) => {\n const dangerousSql = await readInput(\n opts.sql,\n '--sql is required (use a path or \"-\" for stdin).',\n );\n const contextSql = opts.context ? await fs.readFile(String(opts.context), 'utf8') : undefined;\n\n const finding: safety.SafetyFinding = {\n code: String(opts.code) as safety.SafetyFindingCode,\n category: 'DESTRUCTIVE',\n fqn: String(opts.fqn),\n objectType: String(opts.objectType) as safety.SafetyFinding['objectType'],\n reason: String(opts.reason),\n gate: opts.gate ? (String(opts.gate) as safety.SafetyGate) : undefined,\n };\n\n const result = await saferAlternative.suggestSaferAlternative(\n {\n finding,\n dangerousSql,\n contextSql,\n intentNotes: opts.intent ? String(opts.intent) : undefined,\n },\n {\n completeFn: async (prompt) => {\n const r = await ai.complete([{ role: 'user', content: prompt }], {\n feature: 'safer-alternative',\n maxSpendUsd: Number(opts.aiMaxSpend ?? '0') || 0,\n });\n return r.text;\n },\n },\n );\n\n if (String(opts.format).toLowerCase() === 'json') {\n const { rawModelText: _omit, ...keep } = result;\n console.log(JSON.stringify(keep, null, 2));\n return;\n }\n\n console.log(`Confidence: ${result.confidence}${result.parseFailed ? ' (parse failed)' : ''}`);\n console.log(`Reasoning: ${result.reasoning}`);\n if (result.alternativeSql) {\n console.log('');\n console.log('--- Proposed safer DDL ---');\n console.log(result.alternativeSql);\n } else {\n console.warn('No safer alternative SQL was returned.');\n }\n if (result.requiredGates.length > 0) {\n console.log(`Required gates: ${result.requiredGates.join(', ')}`);\n }\n });\n return cmd;\n}\n\nasync function readInput(pathOrDash: unknown, missingMessage: string): Promise<string> {\n if (!pathOrDash) throw new Error(missingMessage);\n const p = String(pathOrDash);\n if (p === '-') {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : (chunk as Buffer));\n }\n return Buffer.concat(chunks).toString('utf8');\n }\n return fs.readFile(p, 'utf8');\n}\n","/**\n * `ddt sketch <kind>` — generate idiomatic Databricks UC DDL from a free-form\n * prose description via the configured AI provider.\n *\n * Composes `@ddt-tools/core/objectSketch.sketchToDdl` with `@ddt-tools/core/ai.complete`.\n * Output is always wrapped in a \"REVIEW BEFORE DEPLOY\" header so the user\n * never confuses model output with hand-authored DDL.\n *\n * Inputs:\n * <kind> managed-table | external-table | streaming-table\n * | materialized-view | view | function | volume\n * --description <text> Free-form description (or \"-\" to read from stdin)\n * --target <fqn> Optional target FQN (e.g. analytics.public.orders)\n * --context <text> Optional additional context\n * --out <path> Optional output file. Default: stdout.\n * --format <fmt> text | json. Default text (just the DDL).\n */\nimport { promises as fs } from 'node:fs';\nimport { Command } from 'commander';\nimport { ai, objectSketch } from '@ddt-tools/core';\n\nconst KINDS = [\n 'managed-table',\n 'external-table',\n 'streaming-table',\n 'materialized-view',\n 'view',\n 'function',\n 'volume',\n] as const;\n\ntype Kind = (typeof KINDS)[number];\n\nexport function sketchCommand(): Command {\n const cmd = new Command('sketch');\n cmd\n .description(\n 'AI-assist: scaffold idiomatic Databricks UC DDL from a prose description. Output always carries a REVIEW BEFORE DEPLOY header.',\n )\n .argument('<kind>', `Object kind: ${KINDS.join(' | ')}`)\n .requiredOption('--description <text>', 'Free-form description. Use \"-\" to read from stdin.')\n .option('--target <fqn>', 'Target FQN (e.g. analytics.public.orders).')\n .option('--context <text>', 'Optional additional context (e.g. \"use SQL warehouse small\").')\n .option('--out <path>', 'Output file. Default stdout.')\n .option('--format <fmt>', 'Output format: text | json. Default text.', 'text')\n .option(\n '--ai-max-spend <usd>',\n \"Refuse the call if today's estimated spend ≥ this (USD). 0 = no cap.\",\n '0',\n )\n .action(async (kindArg, opts) => {\n const kind = String(kindArg).toLowerCase() as Kind;\n if (!KINDS.includes(kind)) {\n throw new Error(`Unknown kind \"${kindArg}\". Use one of: ${KINDS.join(' | ')}`);\n }\n\n const description =\n String(opts.description) === '-' ? await readStdin() : String(opts.description);\n const targetFqn = opts.target ? splitFqn(String(opts.target)) : undefined;\n\n const result = await objectSketch.sketchToDdl(\n {\n description,\n objectKind: kind,\n targetFqn,\n additionalContext: opts.context ? String(opts.context) : undefined,\n },\n {\n completeFn: async (prompt) => {\n const r = await ai.complete([{ role: 'user', content: prompt }], {\n feature: 'object-sketch',\n maxSpendUsd: Number(opts.aiMaxSpend ?? '0') || 0,\n });\n return r.text;\n },\n },\n );\n\n const output =\n String(opts.format).toLowerCase() === 'json'\n ? JSON.stringify({ ...result, rawModelText: undefined }, null, 2)\n : result.generatedSql;\n\n if (opts.out) {\n await fs.writeFile(String(opts.out), output, 'utf8');\n console.log(`Wrote ${String(opts.out)} (${output.length} bytes)`);\n } else {\n console.log(output);\n }\n\n if (result.assumptions.length > 0) {\n console.error('');\n console.error('Model assumptions:');\n for (const a of result.assumptions) console.error(` - ${a}`);\n }\n if (result.parseFailed) {\n console.warn('Model output could not be parsed — see the raw text via --format json.');\n }\n });\n return cmd;\n}\n\nfunction splitFqn(fqn: string): { catalog?: string; schema?: string; name: string } {\n const parts = fqn.split('.');\n if (parts.length === 1) return { name: parts[0]! };\n if (parts.length === 2) return { schema: parts[0], name: parts[1]! };\n if (parts.length === 3) return { catalog: parts[0], schema: parts[1], name: parts[2]! };\n throw new Error(`Invalid --target \"${fqn}\": expected 1, 2, or 3 dot-separated parts.`);\n}\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : (chunk as Buffer));\n }\n return Buffer.concat(chunks).toString('utf8');\n}\n","/**\n * `ddt design <kind>` — AI-assisted schema-design surface.\n *\n * v1 supports `star` — generative star-schema designer that returns a\n * `template star` invocation tuned to a prose domain description.\n * Composes `@ddt-tools/core/designStar.designStar` with `ai.complete` so the\n * CLI is a thin adapter; the prompt-building + parser live in core for\n * shared testability with the MCP/LSP/VS Code hosts.\n *\n * Mirrors `sdt design`.\n */\nimport { Command } from 'commander';\nimport { ai, designSnowflakeSchema, designStar } from '@ddt-tools/core';\n\nconst KINDS = ['star'] as const;\ntype Kind = (typeof KINDS)[number];\n\nexport function designCommand(): Command {\n const cmd = new Command('design');\n cmd.description(\n 'AI-assist: generative schema-design scaffolds. Output always carries a REVIEW BEFORE RUNNING header.',\n );\n\n cmd\n .command('star')\n .description(\n 'Propose a star-schema (fact + dimensions) for the described domain. ' +\n 'Returns a `ddt template star` invocation you can review and run.',\n )\n .requiredOption(\n '--description <text>',\n 'Free-form domain description. Use \"-\" to read from stdin.',\n )\n .option('--target <fqn>', 'Optional target FQN (e.g. main.bronze).')\n .option('--context <text>', 'Optional extra constraints.')\n .option('--format <fmt>', 'Output format: text | json. Default text.', 'text')\n .option(\n '--ai-max-spend <usd>',\n \"Refuse the call if today's estimated spend ≥ this (USD). 0 = no cap.\",\n '0',\n )\n .action(async (opts) => {\n await runDesign('star', opts);\n });\n\n cmd\n .command('snowflake-schema')\n .description(\n 'Refactor a star into a snowflake schema. AI proposes which dims to normalize ' +\n 'into parent/child pairs based on a prose refinement (e.g. \"normalize geography down to country\"). ' +\n 'Returns a reviewable script with `ddt template scd1` calls + manual bridge-wiring steps.',\n )\n .requiredOption('--fact <name>', 'Fact-table name (lowercase identifier).')\n .requiredOption('--dims <list>', 'Comma-separated list of existing dimensions on the star.')\n .requiredOption(\n '--refinement <text>',\n 'Free-form description of the desired snowflake refactor. Use \"-\" to read from stdin.',\n )\n .option('--target <fqn>', 'Optional target FQN (e.g. main.bronze).')\n .option('--context <text>', 'Optional extra constraints.')\n .option('--format <fmt>', 'Output format: text | json. Default text.', 'text')\n .option(\n '--ai-max-spend <usd>',\n \"Refuse the call if today's estimated spend ≥ this (USD). 0 = no cap.\",\n '0',\n )\n .action(async (opts) => {\n await runDesignSnowflakeSchema(opts);\n });\n\n return cmd;\n}\n\nasync function runDesignSnowflakeSchema(opts: Record<string, unknown>): Promise<void> {\n const refinement = String(opts.refinement) === '-' ? await readStdin() : String(opts.refinement);\n const targetFqn = opts.target ? splitFqn(String(opts.target)) : undefined;\n const dimensions = String(opts.dims)\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean);\n\n if (dimensions.length === 0) {\n throw new Error('--dims must include at least one dimension.');\n }\n\n const result = await designSnowflakeSchema.designSnowflakeSchema(\n {\n factName: String(opts.fact),\n dimensions,\n refinement,\n ...(targetFqn ? { targetFqn } : {}),\n ...(opts.context ? { additionalContext: String(opts.context) } : {}),\n },\n {\n completeFn: async (prompt) => {\n const r = await ai.complete([{ role: 'user', content: prompt }], {\n feature: 'design-snowflake-schema',\n maxSpendUsd: Number(opts.aiMaxSpend ?? '0') || 0,\n });\n return r.text;\n },\n },\n 'ddt',\n );\n\n if (String(opts.format).toLowerCase() === 'json') {\n const { rawModelText: _omit, ...keep } = result;\n console.log(JSON.stringify(keep, null, 2));\n return;\n }\n\n console.log(result.proposedInvocation);\n if (result.assumptions.length > 0) {\n console.error('');\n console.error('Model assumptions:');\n for (const a of result.assumptions) console.error(` - ${a}`);\n }\n if (result.parseFailed) {\n console.warn('Model output could not be parsed — see the raw text via --format json.');\n }\n}\n\nasync function runDesign(kind: Kind, opts: Record<string, unknown>): Promise<void> {\n if (!KINDS.includes(kind)) {\n throw new Error(`Unknown kind \"${kind}\". Use one of: ${KINDS.join(' | ')}`);\n }\n const description =\n String(opts.description) === '-' ? await readStdin() : String(opts.description);\n const targetFqn = opts.target ? splitFqn(String(opts.target)) : undefined;\n\n const result = await designStar.designStar(\n {\n description,\n ...(targetFqn ? { targetFqn } : {}),\n ...(opts.context ? { additionalContext: String(opts.context) } : {}),\n },\n {\n completeFn: async (prompt) => {\n const r = await ai.complete([{ role: 'user', content: prompt }], {\n feature: 'design-star',\n maxSpendUsd: Number(opts.aiMaxSpend ?? '0') || 0,\n });\n return r.text;\n },\n },\n 'ddt',\n );\n\n if (String(opts.format).toLowerCase() === 'json') {\n const { rawModelText: _omit, ...keep } = result;\n console.log(JSON.stringify(keep, null, 2));\n return;\n }\n\n console.log(result.proposedInvocation);\n if (result.assumptions.length > 0) {\n console.error('');\n console.error('Model assumptions:');\n for (const a of result.assumptions) console.error(` - ${a}`);\n }\n if (result.parseFailed) {\n console.warn('Model output could not be parsed — see the raw text via --format json.');\n }\n}\n\nfunction splitFqn(fqn: string): { database?: string; schema?: string } {\n const parts = fqn.split('.');\n if (parts.length === 1) return { database: parts[0] };\n if (parts.length === 2) return { database: parts[0]!, schema: parts[1] };\n throw new Error(\n `Invalid --target \"${fqn}\": expected 1 or 2 dot-separated parts (catalog[.schema]).`,\n );\n}\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : (chunk as Buffer));\n }\n return Buffer.concat(chunks).toString('utf8');\n}\n","/**\n * `ddt optimize` — heuristic optimizer. Walks the model and surfaces\n * ranked recommendations (Z-ORDER, unbounded ENUM-shaped strings,\n * missing PKs, streaming-table refresh schedules). Composes with\n * `--explain` so the configured AI provider can re-rank.\n *\n * Mirrors `sdt optimize`.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport {\n loadProject,\n optimize,\n pac,\n parseProjectModel,\n type DatabricksObject,\n} from '@ddt-tools/core';\nimport { attachExplainFlag, runExplain } from '../util/ai-explain.js';\n\nexport function optimizeCommand(): Command {\n const cmd = new Command('optimize');\n cmd\n .description(\n 'Surface ranked optimization recommendations (Z-ORDER, ENUM-shaped strings, missing PKs, streaming-table schedule).',\n )\n .requiredOption('--source <path>', '.ddtproj or .ddtpac to analyze.')\n .option('--format <fmt>', 'table | json | markdown. Default table.', 'table')\n .option('--severity <level>', 'Filter: high | medium | low | info. Default all.', 'all')\n .option('-o, --out <path>', 'Output file. Defaults to stdout.')\n .action(async (opts) => {\n const model = await loadModel(String(opts.source));\n const report = optimize.optimize(model);\n const severity = String(opts.severity ?? 'all').toLowerCase();\n const filtered =\n severity === 'all'\n ? report.recommendations\n : report.recommendations.filter((r) => r.severity === severity);\n\n const fmt = String(opts.format ?? 'table').toLowerCase();\n let payload: string;\n if (fmt === 'json') {\n payload = JSON.stringify({ ...report, recommendations: filtered }, null, 2);\n } else if (fmt === 'markdown') {\n payload = renderMarkdown(filtered, report.stats.objectsScanned);\n } else {\n payload = renderTable(filtered, report.stats.objectsScanned);\n }\n\n if (opts.out) {\n const p = path.resolve(String(opts.out));\n await fs.mkdir(path.dirname(p), { recursive: true });\n await fs.writeFile(p, payload + (payload.endsWith('\\n') ? '' : '\\n'), 'utf8');\n console.error(`Wrote ${p}.`);\n } else {\n process.stdout.write(payload + (payload.endsWith('\\n') ? '' : '\\n'));\n }\n\n await runExplain(\n {\n feature: 'optimize.explain',\n systemPrompt:\n \"You are a Databricks performance engineer. Walk the team through these optimization recommendations: which would have the biggest DBU-cost impact, which are stylistic, which depend on workload characteristics the static scan can't see. Suggest an order to apply them.\",\n },\n opts as { explain?: boolean },\n () =>\n `Recommendations (JSON):\\n\\n${JSON.stringify(filtered, null, 2)}\\n\\nNarrate for a teammate.`,\n );\n });\n attachExplainFlag(cmd);\n return cmd;\n}\n\nasync function loadModel(sourcePath: string): Promise<readonly DatabricksObject[]> {\n if (sourcePath.endsWith('.ddtpac')) {\n const c = await pac.readPac(sourcePath);\n return c.model;\n }\n const loaded = await loadProject(sourcePath);\n return (await parseProjectModel(loaded)) as DatabricksObject[];\n}\n\nfunction renderTable(recs: readonly optimize.OptimizeRecommendation[], scanned: number): string {\n const lines: string[] = [];\n lines.push(`Optimize — ${scanned} object(s) scanned, ${recs.length} recommendation(s).`);\n lines.push('');\n if (recs.length === 0) {\n lines.push(' ✓ No recommendations — the model looks healthy by these heuristics.');\n return lines.join('\\n');\n }\n const sevW = 8;\n const idW = Math.max(20, ...recs.map((r) => r.id.length));\n const fqnW = Math.max(20, ...recs.map((r) => r.fqn.length));\n for (const r of recs) {\n lines.push(\n ` ${r.severity.toUpperCase().padEnd(sevW)} ${r.id.padEnd(idW)} ${r.fqn.padEnd(fqnW)} ${r.summary}`,\n );\n }\n return lines.join('\\n');\n}\n\nfunction renderMarkdown(recs: readonly optimize.OptimizeRecommendation[], scanned: number): string {\n const lines: string[] = [];\n lines.push(`# Optimize recommendations`);\n lines.push('');\n lines.push(`**Scanned:** ${scanned} object(s) — **${recs.length} recommendation(s)**.`);\n lines.push('');\n for (const r of recs) {\n lines.push(`## ${r.severity.toUpperCase()} · \\`${r.id}\\` — \\`${r.fqn}\\``);\n lines.push('');\n lines.push(r.summary);\n lines.push('');\n lines.push('**Suggestion:**');\n lines.push('```sql');\n lines.push(r.suggestion);\n lines.push('```');\n lines.push('');\n lines.push('**Why:** ' + r.rationale);\n lines.push('');\n }\n return lines.join('\\n');\n}\n","/**\n * `ddt rollback-suggest` — AI Phase 6 #4. Propose a reverse-SQL\n * skeleton for a forward DDL that the deterministic plan-to-steps\n * bridge couldn't invert.\n *\n * The output is intended for review, NOT for automatic execution.\n * Every printed proposal carries a REVIEW BEFORE APPLY header.\n * Wiring this into `ddt revert --manifest` automatically is gated to\n * a future opt-in flag — applying AI-proposed reverse-SQL against a\n * live warehouse needs more guardrails than this command provides.\n *\n * Mirrors `sdt rollback-suggest`.\n */\nimport { promises as fs } from 'node:fs';\nimport { Command } from 'commander';\nimport { ai, aiRollback } from '@ddt-tools/core';\n\nexport function rollbackSuggestCommand(): Command {\n const cmd = new Command('rollback-suggest');\n cmd\n .description(\n 'AI-assist: propose a reverse SQL for a forward DDL when the deterministic ' +\n 'plan-to-steps bridge could not invert it. Output always carries a ' +\n 'REVIEW BEFORE APPLY header. Standalone — not auto-wired into `revert`.',\n )\n .requiredOption(\n '--forward-sql <path>',\n 'Path to a file with the forward DDL. Use \"-\" for stdin.',\n )\n .option('--fqn <fqn>', 'Optional object FQN for context.')\n .option(\n '--object-type <type>',\n 'Optional object type for context (e.g. MANAGED_TABLE, STREAMING_TABLE).',\n )\n .option(\n '--finding <code>',\n 'Optional SafetyFindingCode that motivated the rollback (e.g. DROP_DATA_TABLE).',\n )\n .option('--intent <text>', 'Optional one-sentence operator intent.')\n .option('--format <fmt>', 'Output format: text | json. Default text.', 'text')\n .option(\n '--ai-max-spend <usd>',\n \"Refuse the call if today's estimated spend ≥ this (USD). 0 = no cap.\",\n '0',\n )\n .action(async (opts) => {\n const forwardSql = await readInput(\n opts.forwardSql,\n '--forward-sql is required (path or \"-\" for stdin).',\n );\n\n const result = await aiRollback.suggestRollback(\n {\n forwardSql,\n ...(opts.fqn ? { fqn: String(opts.fqn) } : {}),\n ...(opts.objectType ? { objectType: String(opts.objectType) } : {}),\n ...(opts.finding ? { findingCode: String(opts.finding) } : {}),\n ...(opts.intent ? { intentNotes: String(opts.intent) } : {}),\n },\n {\n completeFn: async (prompt) => {\n const r = await ai.complete([{ role: 'user', content: prompt }], {\n feature: 'rollback-suggest',\n maxSpendUsd: Number(opts.aiMaxSpend ?? '0') || 0,\n });\n return r.text;\n },\n },\n );\n\n if (String(opts.format).toLowerCase() === 'json') {\n const { rawModelText: _omit, ...keep } = result;\n console.log(JSON.stringify(keep, null, 2));\n return;\n }\n\n console.error(\n `Confidence: ${result.confidence}${result.unrecoverable ? ' (UNRECOVERABLE)' : ''}${result.parseFailed ? ' — parse failed' : ''}`,\n );\n console.error(`Reasoning: ${result.reasoning}`);\n console.log('');\n console.log(result.reverseSql);\n if (result.confidence === 'unrecoverable' || result.unrecoverable) {\n process.exitCode = 1;\n }\n });\n return cmd;\n}\n\nasync function readInput(pathOrDash: unknown, missingMessage: string): Promise<string> {\n if (!pathOrDash) throw new Error(missingMessage);\n const p = String(pathOrDash);\n if (p === '-') {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : (chunk as Buffer));\n }\n return Buffer.concat(chunks).toString('utf8');\n }\n return fs.readFile(p, 'utf8');\n}\n","/**\n * `ddt compare-profiles` — manage saved comparison profiles.\n *\n * A profile is \"Source X (connection|pac|project) → Target Y, with these\n * mapping rules\", persisted to `<cwd>/.ddt/compare-profiles.json`. The\n * eventual VS Code webview reads/writes the same store; this CLI gives\n * power-users the same affordances headlessly.\n *\n * Subcommands:\n * list — list all saved profiles (table or JSON)\n * show <id> — print one profile (table or JSON)\n * save — upsert a profile from a JSON file (--json-file <path>) or stdin\n * remove <id> — delete a profile\n * preview <id> — run `previewMatch` over the saved profile's\n * source + target endpoints and report counts +\n * examples of matched / source-only / target-only\n * FQNs. Catches typo'd schema names before a\n * full extract + diff round-trip.\n *\n * `preview` resolves each endpoint locally:\n * - kind=connection — reads the EE1 catalog cache at\n * `<root>/.ddt/cache/<reference>/catalog.msgpack` (legacy\n * `catalog.json` also accepted). Run\n * `ddt catalog refresh --connection <reference>` first.\n * - kind=pac — reads the `.ddtpac` archive at `reference`.\n * - kind=project — reads the `.ddtproj` at `reference`.\n */\nimport { promises as fs } from 'node:fs';\nimport { Command } from 'commander';\nimport { catalog, compareProfiles, loadProject, pac, parseProjectModel } from '@ddt-tools/core';\nimport type { DatabricksObject, FullyQualifiedName } from '@ddt-tools/core/model';\n\nexport function compareProfilesCommand(): Command {\n const cmd = new Command('compare-profiles');\n cmd.description('Manage saved compare profiles (.ddt/compare-profiles.json).');\n\n cmd\n .command('list')\n .description('List every saved profile.')\n .option('--root <path>', 'Project root. Default cwd.', process.cwd())\n .option('--json', 'Emit JSON instead of a human table.')\n .action(async (opts) => {\n const store = new compareProfiles.CompareProfilesStore({ root: String(opts.root) });\n const all = await store.list();\n if (opts.json) {\n console.log(JSON.stringify(all, null, 2));\n return;\n }\n if (all.length === 0) {\n console.log('(no compare profiles saved yet)');\n console.log(` store: ${store.path}`);\n return;\n }\n console.log(`${all.length} compare profile(s):`);\n for (const p of all) {\n console.log(` ${p.id.padEnd(24)} ${p.name}`);\n console.log(` source: ${p.source.kind}=${p.source.reference}`);\n console.log(` target: ${p.target.kind}=${p.target.reference}`);\n console.log(` mappings: ${p.mappings.length} updated: ${p.updatedAt}`);\n }\n });\n\n cmd\n .command('show')\n .description('Show one profile by id.')\n .argument('<id>', 'Profile id (from `compare-profiles list`).')\n .option('--root <path>', 'Project root. Default cwd.', process.cwd())\n .option('--json', 'Emit JSON instead of a human table.')\n .action(async (id, opts) => {\n const store = new compareProfiles.CompareProfilesStore({ root: String(opts.root) });\n const p = await store.get(String(id));\n if (!p) {\n console.error(\n `No profile with id \"${id}\". Run \\`ddt compare-profiles list\\` to enumerate.`,\n );\n process.exitCode = 1;\n return;\n }\n if (opts.json) {\n console.log(JSON.stringify(p, null, 2));\n return;\n }\n console.log(`Profile: ${p.name} (${p.id})`);\n if (p.description) console.log(` ${p.description}`);\n console.log(\n ` source: ${p.source.kind}=${p.source.reference}${p.source.catalog ? ` cat=${p.source.catalog}` : ''}${p.source.schema ? ` schema=${p.source.schema}` : ''}`,\n );\n console.log(\n ` target: ${p.target.kind}=${p.target.reference}${p.target.catalog ? ` cat=${p.target.catalog}` : ''}${p.target.schema ? ` schema=${p.target.schema}` : ''}`,\n );\n console.log(` case-sensitive: ${p.caseSensitive ? 'yes' : 'no'}`);\n console.log(` rewrite-inside-strings: ${p.rewriteInsideStrings ? 'yes' : 'no'}`);\n console.log(` updatedAt: ${p.updatedAt}`);\n if (p.mappings.length === 0) {\n console.log(' mappings: (none — identity)');\n } else {\n console.log(` mappings (${p.mappings.length}):`);\n for (const m of p.mappings) console.log(` ${m.source} => ${m.target}`);\n }\n });\n\n cmd\n .command('save')\n .description('Upsert a profile from a JSON file or stdin.')\n .option('--root <path>', 'Project root. Default cwd.', process.cwd())\n .option('--json-file <path>', 'Path to a JSON file containing one profile. Use \"-\" for stdin.')\n .action(async (opts) => {\n if (!opts.jsonFile) {\n throw new Error('--json-file is required (use a path or \"-\" for stdin).');\n }\n const raw =\n String(opts.jsonFile) === '-'\n ? await readStdin()\n : await fs.readFile(String(opts.jsonFile), 'utf8');\n const parsed = JSON.parse(raw) as compareProfiles.CompareProfile;\n if (!parsed?.id || !parsed?.name || !parsed?.source || !parsed?.target) {\n throw new Error(\n 'Profile JSON must contain at minimum: id, name, source, target. mappings defaults to [].',\n );\n }\n const store = new compareProfiles.CompareProfilesStore({ root: String(opts.root) });\n const stamped = await store.upsert({ ...parsed, mappings: parsed.mappings ?? [] });\n console.log(`Saved profile \"${stamped.name}\" (${stamped.id})`);\n console.log(` store: ${store.path}`);\n });\n\n cmd\n .command('remove')\n .description('Delete one profile by id.')\n .argument('<id>', 'Profile id (from `compare-profiles list`).')\n .option('--root <path>', 'Project root. Default cwd.', process.cwd())\n .action(async (id, opts) => {\n const store = new compareProfiles.CompareProfilesStore({ root: String(opts.root) });\n const removed = await store.remove(String(id));\n if (removed) {\n console.log(`Removed profile \"${id}\".`);\n } else {\n console.warn(`No profile with id \"${id}\" — nothing to remove.`);\n }\n });\n\n cmd\n .command('preview')\n .description(\n \"Preview which FQNs match between the profile's source and target. Local-only — no workspace round-trip.\",\n )\n .argument('<id>', 'Profile id (from `compare-profiles list`).')\n .option('--root <path>', 'Project root. Default cwd.', process.cwd())\n .option(\n '--examples <n>',\n 'Max example FQNs to show per bucket in human output. Default 5.',\n (v) => parseInt(v, 10),\n 5,\n )\n .option('--json', 'Emit the full PreviewSummary as JSON.')\n .action(async (id, opts) => {\n const store = new compareProfiles.CompareProfilesStore({ root: String(opts.root) });\n const profile = await store.get(String(id));\n if (!profile) {\n console.error(\n `No profile with id \"${id}\". Run \\`ddt compare-profiles list\\` to enumerate.`,\n );\n process.exitCode = 1;\n return;\n }\n\n const root = String(opts.root);\n const source = await resolveEndpointFqns(profile.source, root);\n const target = await resolveEndpointFqns(profile.target, root);\n\n const summary = compareProfiles.previewMatch({\n source: source.fqns,\n target: target.fqns,\n mappings: profile.mappings,\n ...(profile.caseSensitive ? { caseSensitive: true } : {}),\n });\n\n if (opts.json) {\n console.log(\n JSON.stringify(\n {\n profile: { id: profile.id, name: profile.name },\n source: {\n kind: profile.source.kind,\n reference: profile.source.reference,\n count: source.fqns.length,\n },\n target: {\n kind: profile.target.kind,\n reference: profile.target.reference,\n count: target.fqns.length,\n },\n summary,\n },\n null,\n 2,\n ),\n );\n return;\n }\n\n console.log(`Preview: ${profile.name} (${profile.id})`);\n console.log(\n ` source (${profile.source.kind}=${profile.source.reference}): ${source.fqns.length} object(s)${source.note ? ` — ${source.note}` : ''}`,\n );\n console.log(\n ` target (${profile.target.kind}=${profile.target.reference}): ${target.fqns.length} object(s)${target.note ? ` — ${target.note}` : ''}`,\n );\n console.log('');\n console.log(` matched: ${summary.matchedCount}`);\n console.log(` source-only: ${summary.sourceOnlyCount}`);\n console.log(` target-only: ${summary.targetOnlyCount}`);\n\n const exN = Math.max(0, Number(opts.examples));\n printBucket('matched', summary.matched, exN);\n printBucket('source-only', summary.sourceOnly, exN);\n printBucket('target-only', summary.targetOnly, exN);\n\n if (\n summary.matchedCount === 0 &&\n (summary.sourceOnlyCount > 0 || summary.targetOnlyCount > 0)\n ) {\n console.warn(\"No FQNs matched — check the profile's scope and mapping rules.\");\n }\n });\n\n return cmd;\n}\n\ninterface EndpointResolution {\n fqns: FullyQualifiedName[];\n note?: string;\n}\n\nasync function resolveEndpointFqns(\n endpoint: compareProfiles.CompareProfile['source'],\n root: string,\n): Promise<EndpointResolution> {\n if (endpoint.kind === 'connection') {\n const cache = new catalog.CatalogCache({ root, connection: endpoint.reference });\n const snapshot = await cache.get();\n if (snapshot.catalogs.length === 0) {\n return {\n fqns: [],\n note: `empty catalog cache at ${cache.path} — run \\`ddt catalog refresh --connection ${endpoint.reference}\\` first`,\n };\n }\n return { fqns: fqnsFromSnapshot(snapshot, endpoint.catalog, endpoint.schema) };\n }\n if (endpoint.kind === 'pac') {\n const contents = await pac.readPac(endpoint.reference);\n return { fqns: fqnsFromObjects(contents.model, endpoint.catalog, endpoint.schema) };\n }\n // kind === 'project'\n const loaded = await loadProject(endpoint.reference);\n const model = await parseProjectModel(loaded);\n return { fqns: fqnsFromObjects(model, endpoint.catalog, endpoint.schema) };\n}\n\nfunction fqnsFromSnapshot(\n snapshot: catalog.CatalogSnapshot,\n catalogScope: string | undefined,\n schemaScope: string | undefined,\n): FullyQualifiedName[] {\n const sameId = (a: string | undefined, b: string | undefined): boolean =>\n !!a && !!b && a.toUpperCase() === b.toUpperCase();\n const out: FullyQualifiedName[] = [];\n for (const cat of snapshot.catalogs) {\n if (catalogScope && !sameId(cat.catalog, catalogScope)) continue;\n for (const sc of cat.schemas) {\n if (schemaScope && !sameId(sc.schema, schemaScope)) continue;\n for (const obj of sc.objects) {\n // FQN uses `database` for UC's catalog — paired-file convention.\n out.push({ database: obj.catalog, schema: obj.schema, name: obj.name });\n }\n }\n }\n return out;\n}\n\nfunction fqnsFromObjects(\n model: readonly DatabricksObject[],\n catalogScope: string | undefined,\n schemaScope: string | undefined,\n): FullyQualifiedName[] {\n const sameId = (a: string | undefined, b: string | undefined): boolean =>\n !!a && !!b && a.toUpperCase() === b.toUpperCase();\n const out: FullyQualifiedName[] = [];\n for (const obj of model) {\n // FQN uses `database` for UC's catalog — paired-file convention.\n if (catalogScope && !sameId(obj.fqn.database, catalogScope)) continue;\n if (schemaScope && !sameId(obj.fqn.schema, schemaScope)) continue;\n out.push(obj.fqn);\n }\n return out;\n}\n\nfunction printBucket(label: string, items: readonly string[], exampleN: number): void {\n if (items.length === 0) return;\n console.log('');\n console.log(\n ` ${label} examples (showing ${Math.min(exampleN, items.length)} of ${items.length}):`,\n );\n for (const fqn of items.slice(0, exampleN)) console.log(` ${fqn}`);\n}\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : (chunk as Buffer));\n }\n return Buffer.concat(chunks).toString('utf8');\n}\n","/**\n * `ddt explorer` — ASCII tree dump of the live catalog/schema/object\n * hierarchy for a connected target, read from the EE1 catalog cache.\n *\n * The eventual VS Code TreeDataProvider walks the same `treeForSnapshot`\n * shape; this CLI gives non-VS-Code users the same browsable view of the\n * cached catalog. No live queries are issued — the cache is read-only.\n * Run `ddt catalog refresh --connection <name>` first to populate it.\n *\n * Inputs:\n * --connection <name> Required. Connection profile name to load the cache for.\n * --root <path> Project root (where .ddt/cache/ lives). Default cwd.\n * --filter <query> Typeahead filter; case-insensitive substring match.\n * Keeps every ancestor of a leaf match.\n * --json Emit the tree as JSON instead of an ASCII tree.\n */\nimport { Command } from 'commander';\nimport { catalog, objectExplorer } from '@ddt-tools/core';\n\nexport function explorerCommand(): Command {\n const cmd = new Command('explorer');\n cmd\n .description(\n 'ASCII tree dump of the cached catalog for a connection. Run `ddt catalog refresh` first to populate.',\n )\n .requiredOption('--connection <name>', 'Connection profile name (the cache subfolder).')\n .option('--root <path>', 'Project root. Default cwd.', process.cwd())\n .option('--filter <query>', 'Typeahead substring filter (case-insensitive).')\n .option(\n '--depth <n>',\n 'Truncate tree at depth N (0 = root only, 1 = +catalogs, 2 = +schemas, 3 = +object-groups, 4 = +objects). Default unlimited.',\n (v) => parseInt(v, 10),\n )\n .option('--json', 'Emit tree as JSON instead of ASCII.')\n .action(async (opts) => {\n const cache = new catalog.CatalogCache({\n root: String(opts.root),\n connection: String(opts.connection),\n });\n const snapshot = await cache.get();\n let tree = objectExplorer.treeForSnapshot(snapshot);\n if (opts.filter) tree = objectExplorer.filterTree(tree, String(opts.filter));\n if (typeof opts.depth === 'number') tree = objectExplorer.truncateTree(tree, opts.depth);\n\n if (snapshot.catalogs.length === 0) {\n console.warn(`Catalog cache is empty for connection \"${opts.connection}\".`);\n console.warn(` Cache file: ${cache.path}`);\n console.warn(` Run \\`ddt catalog refresh --connection ${opts.connection}\\` to populate.`);\n return;\n }\n\n if (opts.json) {\n console.log(JSON.stringify(tree, null, 2));\n return;\n }\n\n renderAsciiTree(tree);\n });\n return cmd;\n}\n\n/**\n * Render the explorer tree as an ASCII tree (├──, │, └──). Mirrors the\n * GNU `tree`(1) glyph set for familiarity. Root prints without a\n * connector; descendants get the standard branch glyphs.\n */\nfunction renderAsciiTree(root: objectExplorer.ExplorerNode): void {\n const desc = root.description ? ` (${root.description})` : '';\n console.log(`${root.label}${desc}`);\n const children = root.children ?? [];\n for (let i = 0; i < children.length; i++) {\n renderChild(children[i]!, '', i === children.length - 1);\n }\n}\n\nfunction renderChild(node: objectExplorer.ExplorerNode, prefix: string, isLast: boolean): void {\n const connector = isLast ? '└── ' : '├── ';\n const desc = node.description ? ` (${node.description})` : '';\n console.log(`${prefix}${connector}${node.label}${desc}`);\n const children = node.children ?? [];\n const childPrefix = prefix + (isLast ? ' ' : '│ ');\n for (let i = 0; i < children.length; i++) {\n renderChild(children[i]!, childPrefix, i === children.length - 1);\n }\n}\n","/**\n * `ddt catalog` — manage the per-connection catalog cache (EE1 substrate).\n *\n * ddt catalog refresh --connection <name> [--catalogs <csv>] [--concurrency <n>]\n * ddt catalog show --connection <name> [--json]\n * ddt catalog clear --connection <name>\n *\n * `refresh` opens a live Databricks SQL warehouse connection, discovers\n * catalogs via `SHOW CATALOGS`, runs the bulk-scan SQL per catalog via\n * the bounded promise pool, and writes the assembled snapshot to\n * `<root>/.ddt/cache/<conn>/catalog.msgpack` (RES.1 — was `catalog.json`\n * before 2026-05-16; the cache reader still accepts the legacy form for\n * one major version). Schema fingerprints (`MAX(LAST_ALTERED)`) are\n * checked first; catalogs that haven't changed since the last refresh\n * are skipped.\n *\n * `show` reads the cache file and pretty-prints (or emits JSON).\n * `clear` deletes the cache file (and its parent dir if empty).\n *\n * Object Explorer (`ddt explorer`) and the eventual EE2 intellisense\n * provider both consume this cache.\n */\nimport { Command } from 'commander';\nimport { catalog, createConnection, getProfile, type DatabricksConnection } from '@ddt-tools/core';\n\n/**\n * Built-in catalogs that almost no one wants in their cache. Pass\n * `--include-builtins` to keep them. `system` is intentionally excluded\n * because the bulk-scan SQL filters out `information_schema` already.\n */\nconst BUILTIN_CATALOGS = new Set(['system', 'samples', '__databricks_internal']);\n\ninterface ShowCatalogsRow {\n catalog?: string;\n catalog_name?: string;\n CATALOG?: string;\n CATALOG_NAME?: string;\n}\n\nexport function catalogCommand(): Command {\n const cmd = new Command('catalog');\n cmd.description(\n 'Manage the per-connection catalog cache used by the Object Explorer + EE2 intellisense.',\n );\n\n cmd\n .command('refresh')\n .description('Open the connection, scan every (non-builtin) catalog, write the catalog cache.')\n .requiredOption('-c, --connection <name>', 'Connection profile name.')\n .option('--root <path>', 'Project root. Default cwd.', process.cwd())\n .option('--catalogs <csv>', 'Comma-separated list. Default: every non-builtin catalog.')\n .option('--include-builtins', 'Include system / samples / __databricks_internal.', false)\n .option(\n '--concurrency <n>',\n 'Bounded-concurrency cap for the bulk-scan pool. Default 10.',\n '10',\n )\n .option('--no-fingerprint-skip', 'Force a full scan even when fingerprints are unchanged.')\n .action(async (opts) => {\n const profile = await getProfile(String(opts.connection));\n const conn = createConnection(profile);\n const cache = new catalog.CatalogCache({\n root: String(opts.root),\n connection: profile.name,\n });\n\n console.log(`Connecting to ${profile.auth.host}…`);\n await conn.connect();\n try {\n const cats = await resolveCatalogs(conn, opts);\n if (cats.length === 0) {\n console.warn('No catalogs to scan. Pass --catalogs or --include-builtins.');\n return;\n }\n console.log(\n `Scanning ${cats.length} catalog(s) with concurrency ${Number(opts.concurrency)}.`,\n );\n\n const cached = await cache.get();\n const cachedByCat = new Map(cached.catalogs.map((c) => [c.catalog, c] as const));\n\n const concurrency = Math.max(1, Number(opts.concurrency) || 10);\n const fingerprintSkip = opts.fingerprintSkip !== false;\n\n const { results, errors } = await catalog.mapPool(\n cats,\n async (cat) => {\n let freshFingerprint: number | null = null;\n try {\n const fpRes = await conn.query<{ MAX_LAST_ALTERED: unknown }>(\n catalog.fingerprintSqlForCatalog(cat),\n );\n freshFingerprint = catalog.parseFingerprintRow(fpRes.rows);\n } catch (err) {\n console.warn(\n `fingerprint(${cat}) failed; falling through to full scan: ${(err as Error).message}`,\n );\n }\n\n const cachedCat = cachedByCat.get(cat);\n if (\n fingerprintSkip &&\n cachedCat &&\n cachedCat.fingerprint != null &&\n freshFingerprint != null &&\n catalog.isFresh(cachedCat.fingerprint, freshFingerprint)\n ) {\n console.log(` ${cat}: fresh; reusing cache`);\n return {\n catalog: cat,\n fingerprint: cachedCat.fingerprint,\n schemas: cachedCat.schemas,\n };\n }\n\n const scanRes = await conn.query(catalog.bulkScanSqlForCatalog(cat));\n const schemas = catalog.parseBulkScanRows(cat, scanRes.rows);\n const fingerprint = freshFingerprint ?? null;\n console.log(\n ` ${cat}: ${schemas.length} schemas / ${schemas.reduce((sum, s) => sum + s.objects.length, 0)} objects`,\n );\n return { catalog: cat, fingerprint, schemas };\n },\n { concurrency },\n );\n\n for (const e of errors) {\n console.warn(`scan failed for \"${cats[e.index]}\": ${(e.error as Error).message}`);\n }\n\n const snapshot = catalog.refreshFingerprints({\n version: catalog.CATALOG_SNAPSHOT_VERSION,\n connection: profile.name,\n snapshotAt: new Date().toISOString(),\n fingerprint: null,\n catalogs: results.filter((r): r is NonNullable<typeof r> => !!r),\n });\n await cache.set(snapshot);\n\n console.log(`Wrote ${snapshot.catalogs.length} catalogs to ${cache.path}`);\n } finally {\n await conn.disconnect();\n }\n });\n\n cmd\n .command('show')\n .description('Pretty-print or JSON-dump the cached snapshot for a connection.')\n .requiredOption('-c, --connection <name>', 'Connection profile name.')\n .option('--root <path>', 'Project root. Default cwd.', process.cwd())\n .option('--json', 'Emit JSON instead of summary.')\n .action(async (opts) => {\n const cache = new catalog.CatalogCache({\n root: String(opts.root),\n connection: String(opts.connection),\n });\n const snapshot = await cache.get();\n if (opts.json) {\n console.log(JSON.stringify(snapshot, null, 2));\n return;\n }\n if (snapshot.catalogs.length === 0) {\n console.warn(`Catalog cache is empty for \"${opts.connection}\".`);\n console.warn(` Cache file: ${cache.path}`);\n console.warn(` Run \\`ddt catalog refresh --connection ${opts.connection}\\` to populate.`);\n return;\n }\n console.log(`Snapshot for \"${snapshot.connection}\" — ${snapshot.snapshotAt}`);\n console.log(\n ` Top-level fingerprint: ${snapshot.fingerprint != null ? new Date(snapshot.fingerprint).toISOString() : '(none)'}`,\n );\n for (const cat of snapshot.catalogs) {\n const objCount = cat.schemas.reduce((sum, s) => sum + s.objects.length, 0);\n console.log(\n ` ${cat.catalog.padEnd(32)} ${cat.schemas.length} schemas / ${objCount} objects`,\n );\n }\n });\n\n cmd\n .command('clear')\n .description('Delete the cached snapshot for a connection.')\n .requiredOption('-c, --connection <name>', 'Connection profile name.')\n .option('--root <path>', 'Project root. Default cwd.', process.cwd())\n .action(async (opts) => {\n const cache = new catalog.CatalogCache({\n root: String(opts.root),\n connection: String(opts.connection),\n });\n await cache.clear();\n console.log(`Cleared cache for \"${opts.connection}\".`);\n console.log(` was: ${cache.path}`);\n });\n\n return cmd;\n}\n\nasync function resolveCatalogs(\n conn: DatabricksConnection,\n opts: { catalogs?: unknown; includeBuiltins?: unknown },\n): Promise<string[]> {\n if (opts.catalogs) {\n return String(opts.catalogs)\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean);\n }\n const res = await conn.query<ShowCatalogsRow>('SHOW CATALOGS');\n const names = res.rows\n .map((r) => String(r.catalog ?? r.catalog_name ?? r.CATALOG ?? r.CATALOG_NAME ?? ''))\n .filter(Boolean);\n if (opts.includeBuiltins) return names;\n return names.filter((n) => !BUILTIN_CATALOGS.has(n.toLowerCase()));\n}\n","/**\n * Minimal logger used by the CLI. Wraps chalk/ora so a future move to a\n * non-tty mode is centralised.\n */\nimport chalk from 'chalk';\n\nexport const logger = {\n info: (msg: string) => console.log(msg),\n success: (msg: string) => console.log(chalk.green('✔'), msg),\n warn: (msg: string) => console.warn(chalk.yellow('!'), msg),\n error: (msg: string) => console.error(chalk.red('✖'), msg),\n step: (msg: string) => console.log(chalk.cyan('→'), msg),\n dim: (msg: string) => console.log(chalk.gray(msg)),\n};\n","/**\n * `ddt xcompare-ir` — Cross-platform IR compare (XPM.31b).\n *\n * Reads a JSON file of source-platform canonical IRs (typically the\n * Databricks side; reverse-direction inputs are also accepted), runs\n * every IR through the XPM.31a dispatcher, rolls findings up with the\n * XPM.30 cross-platform safety classifier, applies the XPM.32 tier\n * gate, and prints the result.\n *\n * NOTE: this is the IR-level entry point — it does NOT connect to a\n * live warehouse. Live cross-platform compare against a `<sdt-profile>`\n * is a follow-up that requires both halves of the engine to share\n * extractor state (deferred until paid-warehouse access is available\n * for live integration testing).\n *\n * Usage:\n *\n * ddt xcompare-ir --source schema.json \\\n * --tier pro \\\n * --format markdown\n *\n * ddt xcompare-ir --source schema.json \\\n * --tier enterprise \\\n * --format json \\\n * --allow-destructive --allow-unmappable\n *\n * Input JSON shape: array of `XpmObjectIr` (see `@xpm/migrate/canonicalIr`).\n *\n * Exit codes:\n * 0 — assessment is OK / INFO / DESTRUCTIVE-with-override / UNRECOVERABLE-with-override.\n * 2 — assessment is DESTRUCTIVE without --allow-destructive, or\n * UNRECOVERABLE without --allow-unmappable.\n * 1 — invalid input / file not found / parse error.\n */\nimport { Command } from 'commander';\nimport { promises as fs } from 'node:fs';\nimport {\n classifyCrossPlatformDeploy,\n dispatchAll,\n filterAssessmentByTier,\n formatCrossPlatformAssessment,\n isCrossPlatformDeployBlocked,\n isXpmTier,\n type XpmTier,\n} from '@ddt-tools/core/migrate';\nimport type { XpmObjectIr } from '@ddt-tools/core/migrate';\nimport { logger } from '../util/logger.js';\n\nexport function xcompareCommand(): Command {\n const cmd = new Command('xcompare-ir');\n cmd.description(\n 'Cross-platform IR compare (Databricks ↔ Snowflake). Maps source IRs through XPM-Deep substrate; emits tier-gated safety assessment. IR-level only (live-warehouse compare is a follow-up).',\n );\n\n cmd\n .requiredOption('--source <path>', 'JSON file with an array of XpmObjectIr source objects.')\n .option('--tier <tier>', 'License tier: free | pro | team | enterprise.', 'free')\n .option('--format <format>', 'Output format: markdown | json.', 'markdown')\n .option('--allow-destructive', 'Permit DESTRUCTIVE verdicts (exit 0 instead of 2).', false)\n .option(\n '--allow-unmappable',\n 'Permit UNRECOVERABLE verdicts (exit 0 instead of 2). Implies --allow-destructive.',\n false,\n )\n .action(\n async (opts: {\n source: string;\n tier: string;\n format: string;\n allowDestructive: boolean;\n allowUnmappable: boolean;\n }) => {\n if (!isXpmTier(opts.tier)) {\n logger.error(\n `Unknown --tier \"${opts.tier}\". Use one of: free | pro | team | enterprise.`,\n );\n process.exitCode = 1;\n return;\n }\n const tier: XpmTier = opts.tier;\n const format = (opts.format ?? 'markdown').toLowerCase();\n if (format !== 'markdown' && format !== 'json') {\n logger.error(`Unknown --format \"${opts.format}\". Use markdown | json.`);\n process.exitCode = 1;\n return;\n }\n\n let raw: string;\n try {\n raw = await fs.readFile(opts.source, 'utf-8');\n } catch (e) {\n logger.error(`Cannot read --source file '${opts.source}': ${(e as Error).message}`);\n process.exitCode = 1;\n return;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (e) {\n logger.error(`--source file is not valid JSON: ${(e as Error).message}`);\n process.exitCode = 1;\n return;\n }\n\n if (!Array.isArray(parsed)) {\n logger.error(\n `--source file must contain a JSON array of XpmObjectIr objects (got ${typeof parsed}).`,\n );\n process.exitCode = 1;\n return;\n }\n const sources = parsed as readonly XpmObjectIr[];\n\n const dispatched = dispatchAll(sources);\n const assessment = classifyCrossPlatformDeploy(dispatched);\n const tierFiltered = filterAssessmentByTier(assessment, tier);\n\n if (format === 'json') {\n process.stdout.write(JSON.stringify(tierFiltered, null, 2) + '\\n');\n } else {\n process.stdout.write(formatCrossPlatformAssessment(tierFiltered) + '\\n');\n }\n\n if (\n isCrossPlatformDeployBlocked(assessment, {\n destructiveOverride: opts.allowDestructive || opts.allowUnmappable,\n unmappableOverride: opts.allowUnmappable,\n })\n ) {\n process.exitCode = 2;\n }\n },\n );\n\n return cmd;\n}\n","/**\n * `ddt profile <fqn>` — item 4 of the constraint-enforcement initiative.\n *\n * Reads rows from either:\n * - a JSON file (`--rows`), or\n * - a live warehouse (`--live <profile>`) via `DatabricksConnection.executeRows`.\n *\n * Live mode runs `SELECT * FROM <fqn> LIMIT --row-limit` via the SQL\n * Statement Execution API. Composes with `ddt suggest-constraints`.\n *\n * Mirrors `sdt profile`.\n */\nimport { promises as fs } from 'fs';\nimport path from 'path';\nimport { Command } from 'commander';\nimport { profile, createConnection, getProfile } from '@ddt-tools/core';\n\nexport function profileCommand(): Command {\n const cmd = new Command('profile');\n cmd\n .description(\n 'Compute per-column profile statistics (nulls, distinct, min/max, top values) for a table. ' +\n 'Rows are read from a JSON file in v1 (live-warehouse executeRows wiring is a documented follow-up).',\n )\n .argument(\n '<fqn>',\n 'Fully-qualified table name to embed in the profile output (CATALOG.SCHEMA.TABLE).',\n )\n .option(\n '--rows <path>',\n 'JSON file containing the rows to profile (TableRow[]). Mutually exclusive with --live.',\n )\n .option(\n '--live <profile>',\n 'Connection profile name to fetch rows live from Databricks via SELECT * FROM <fqn>. Mutually exclusive with --rows.',\n )\n .option(\n '--row-limit <n>',\n 'Cap rows fetched in live mode. Default 50000. Use 0 for unbounded (DANGER on prod tables).',\n '50000',\n )\n .option(\n '--columns <list>',\n 'Comma-separated column list. Defaults to every key seen in the rows.',\n )\n .option('--top-n <n>', 'Cap the top-values list per column. Default 10.', '10')\n .option(\n '--sampled',\n 'Mark the row set as sampled (caller-supplied sample, not the full table).',\n false,\n )\n .option(\n '--sample-strategy <label>',\n 'Free-form sampling label (e.g. \"TABLESAMPLE(1 PERCENT)\"). Default \"FULL\".',\n )\n .option('--population-rows <n>', 'When --sampled, the full population row count for context.')\n .option('--format <fmt>', 'Output format: json | markdown. Default json.', 'json')\n .option('-o, --output <path>', 'Write the profile to a file instead of stdout.')\n .action(async (fqn: string, opts: Record<string, unknown>) => {\n await runProfile(fqn, opts);\n });\n return cmd;\n}\n\nexport async function runProfile(fqn: string, opts: Record<string, unknown>): Promise<void> {\n const rowsPath = opts.rows as string | undefined;\n const liveProfile = opts.live as string | undefined;\n if (Boolean(rowsPath) === Boolean(liveProfile)) {\n throw new Error('Specify exactly one of --rows or --live.');\n }\n const rows: profile.TableRow[] = liveProfile\n ? await fetchLiveRows(liveProfile, fqn, Number(opts.rowLimit ?? '50000'))\n : await readRowsFile(String(rowsPath));\n const columns = opts.columns\n ? String(opts.columns)\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean)\n : undefined;\n const topN = Number(opts.topN ?? '10') || 10;\n const sampled = opts.sampled === true;\n const populationRowCount = opts.populationRows ? Number(opts.populationRows) : undefined;\n const sampleStrategy = opts.sampleStrategy ? String(opts.sampleStrategy) : undefined;\n\n const tableProfile = profile.analyzeRows(fqn, rows, {\n ...(columns ? { columns } : {}),\n topN,\n sampled,\n ...(populationRowCount !== undefined ? { populationRowCount } : {}),\n ...(sampleStrategy ? { sampleStrategy } : {}),\n });\n\n const format = String(opts.format ?? 'json').toLowerCase();\n const output =\n format === 'markdown'\n ? profile.renderProfileMarkdown(tableProfile)\n : JSON.stringify(tableProfile, null, 2);\n\n if (opts.output) {\n const outPath = path.resolve(String(opts.output));\n await fs.writeFile(outPath, output, 'utf8');\n console.error(`profile: wrote ${outPath} (columns=${tableProfile.columns.length})`);\n } else {\n process.stdout.write(output + '\\n');\n }\n}\n\nasync function readRowsFile(p: string): Promise<profile.TableRow[]> {\n const rowsJson = await fs.readFile(path.resolve(p), 'utf8');\n const rows = JSON.parse(rowsJson) as profile.TableRow[];\n if (!Array.isArray(rows)) {\n throw new Error(`--rows file must contain a TableRow[] (JSON array). Got: ${typeof rows}.`);\n }\n return rows;\n}\n\nasync function fetchLiveRows(\n profileName: string,\n fqn: string,\n rowLimit: number,\n): Promise<profile.TableRow[]> {\n const limit = rowLimit > 0 ? ` LIMIT ${Math.floor(rowLimit)}` : '';\n const sql = `SELECT * FROM ${fqn}${limit}`;\n const cp = await getProfile(profileName);\n const conn = createConnection(cp);\n console.error(`profile: connecting to ${cp.auth.host}…`);\n await conn.connect();\n try {\n const rows = await conn.executeRows(sql);\n console.error(\n `profile: fetched ${rows.length} row(s) from ${fqn}${rowLimit > 0 && rows.length === rowLimit ? ' (LIMIT reached — increase --row-limit for full-table profile)' : ''}.`,\n );\n return rows as profile.TableRow[];\n } finally {\n await conn.disconnect().catch(() => undefined);\n }\n}\n","/**\n * `ddt suggest-constraints <fqn>` — item 5 of the constraint-enforcement\n * initiative. Mirrors `sdt suggest-constraints`.\n */\nimport { promises as fs } from 'fs';\nimport path from 'path';\nimport { Command } from 'commander';\nimport type { profile as profileNs } from '@ddt-tools/core';\nimport { ai, suggestConstraints as core, refactoring } from '@ddt-tools/core';\n\ntype Confidence = 'low' | 'medium' | 'high';\nconst CONFIDENCE_RANK: Record<Confidence, number> = { low: 0, medium: 1, high: 2 };\n\nexport function suggestConstraintsCommand(): Command {\n const cmd = new Command('suggest-constraints');\n cmd\n .description(\n 'Suggest PK/UK/FK/CHECK candidates for a profiled table. Reads a TableProfile JSON ' +\n '(from `ddt profile`) and emits suggestions with confidence tiers + rationale.',\n )\n .argument('<fqn>', 'Fully-qualified table name (must match the profile.fqn).')\n .requiredOption('--profile <path>', 'JSON file containing the TableProfile to analyze.')\n .option(\n '--parents <path>',\n 'JSON file with parent PK directory: [{ fqn, columns }]. Enables FK candidates.',\n )\n .option('--include-low', 'Include low-confidence suggestions. Default: filtered out.', false)\n .option(\n '--default-enforced',\n 'Treat default platform enforcement as true (Lakebase semantics).',\n false,\n )\n .option(\n '--ai',\n 'After heuristic scoring, re-rank by business plausibility via the configured AI provider. Requires `ddt ai` configured.',\n false,\n )\n .option(\n '--ai-context <text>',\n 'Optional one-line context about the table (e.g. \"customer events from the e-commerce app\") to ground the AI re-ranker.',\n )\n .option(\n '--apply-to <refactor-json-path>',\n 'Append included suggestions to a refactor.json file as ADD_CONSTRAINT ops. The file is created if missing; the existing operations array is preserved.',\n )\n .option(\n '--apply-min <tier>',\n 'Minimum confidence tier to apply (low | medium | high). Default: medium.',\n 'medium',\n )\n .option('--format <fmt>', 'Output format: json | markdown. Default markdown.', 'markdown')\n .option('-o, --output <path>', 'Write output to a file instead of stdout.')\n .action(async (fqn: string, opts: Record<string, unknown>) => {\n await runSuggestConstraints(fqn, opts);\n });\n return cmd;\n}\n\nexport async function runSuggestConstraints(\n fqn: string,\n opts: Record<string, unknown>,\n): Promise<void> {\n const profilePath = String(opts.profile);\n const profileJson = await fs.readFile(path.resolve(profilePath), 'utf8');\n const tableProfile = JSON.parse(profileJson) as profileNs.TableProfile;\n if (!tableProfile.fqn || !Array.isArray(tableProfile.columns)) {\n throw new Error(`--profile file is not a TableProfile (missing fqn / columns).`);\n }\n if (tableProfile.fqn !== fqn) {\n console.error(\n `profile fqn \"${tableProfile.fqn}\" does not match argument \"${fqn}\". Using the argument.`,\n );\n tableProfile.fqn = fqn;\n }\n\n let parentPks: Array<{ fqn: string; columns: string[] }> = [];\n if (opts.parents) {\n const parentsJson = await fs.readFile(path.resolve(String(opts.parents)), 'utf8');\n const parsed = JSON.parse(parentsJson);\n if (!Array.isArray(parsed)) {\n throw new Error(`--parents file must be a JSON array of { fqn, columns } entries.`);\n }\n parentPks = parsed;\n }\n\n let suggestions: core.ConstraintSuggestion[] = core.suggestConstraints(tableProfile, {\n parentPks,\n includeLow: opts.includeLow === true,\n defaultEnforced: opts.defaultEnforced === true,\n });\n\n if (opts.ai === true && suggestions.length > 0) {\n try {\n suggestions = await core.rerankWithAi(suggestions, {\n completeFn: async (prompt: string) => {\n const reply = await ai.complete([{ role: 'user', content: prompt }], {\n feature: 'suggest-constraints.rerank',\n });\n return reply.text;\n },\n context: typeof opts.aiContext === 'string' ? opts.aiContext : undefined,\n });\n } catch (err) {\n console.error(\n `--ai re-rank failed; keeping heuristic ordering: ${err instanceof Error ? err.message : String(err)}`,\n );\n console.error('Run `ddt ai status` to verify your AI provider is configured.');\n }\n }\n\n if (opts.applyTo) {\n const applied = await applyToRefactorLog(\n suggestions,\n String(opts.applyTo),\n fqn,\n String(opts.applyMin ?? 'medium').toLowerCase() as Confidence,\n opts.ai === true ? 'ai-rerank' : 'heuristic',\n );\n console.error(\n `--apply-to: appended ${applied} suggestion(s) as ADD_CONSTRAINT ops to ${opts.applyTo} (filtered by min confidence ${opts.applyMin ?? 'medium'}).`,\n );\n }\n\n const format = String(opts.format ?? 'markdown').toLowerCase();\n const output =\n format === 'json'\n ? JSON.stringify(suggestions, null, 2)\n : core.renderSuggestionsMarkdown(suggestions);\n\n if (opts.output) {\n const outPath = path.resolve(String(opts.output));\n await fs.writeFile(outPath, output, 'utf8');\n console.error(`suggest-constraints: wrote ${suggestions.length} suggestion(s) to ${outPath}`);\n } else {\n process.stdout.write(output + (output.endsWith('\\n') ? '' : '\\n'));\n }\n}\n\nasync function applyToRefactorLog(\n suggestions: readonly core.ConstraintSuggestion[],\n refactorJsonPath: string,\n fqn: string,\n minConfidence: Confidence,\n source: 'heuristic' | 'ai-rerank',\n): Promise<number> {\n const fqnParts = fqn.split('.').filter(Boolean);\n if (fqnParts.length < 1) {\n throw new Error(`--apply-to: fqn \"${fqn}\" cannot be parsed`);\n }\n const objectRef = {\n objectType: 'MANAGED_TABLE' as const,\n name: fqnParts[fqnParts.length - 1]!,\n ...(fqnParts.length >= 2 ? { schema: fqnParts[fqnParts.length - 2]! } : {}),\n ...(fqnParts.length >= 3 ? { database: fqnParts[fqnParts.length - 3]! } : {}),\n };\n\n const absPath = path.resolve(refactorJsonPath);\n let log = await refactoring.loadRefactorLog(absPath);\n const minRank = CONFIDENCE_RANK[minConfidence] ?? CONFIDENCE_RANK.medium;\n let appended = 0;\n for (const s of suggestions) {\n if ((CONFIDENCE_RANK[s.confidence as Confidence] ?? 0) < minRank) continue;\n const details: refactoring.AddConstraintOp['details'] = {\n constraintKind: s.kind,\n columns: s.columns,\n fromSuggester: true,\n suggestionSource: source,\n ...(s.references\n ? { referencedFqn: parseFqn(s.references.fqn), referencedColumns: s.references.columns }\n : {}),\n ...(s.predicate ? { expression: s.predicate } : {}),\n };\n log = refactoring.appendOperation(log, {\n type: 'ADD_CONSTRAINT',\n object: objectRef,\n details,\n });\n appended++;\n }\n await refactoring.saveRefactorLog(absPath, log);\n return appended;\n}\n\nfunction parseFqn(s: string): { database?: string; schema?: string; name: string } {\n const parts = s.split('.').filter(Boolean);\n const name = parts[parts.length - 1]!;\n return {\n name,\n ...(parts.length >= 2 ? { schema: parts[parts.length - 2]! } : {}),\n ...(parts.length >= 3 ? { database: parts[parts.length - 3]! } : {}),\n };\n}\n","/**\n * `ddt purge` — DCM compatibility item 2 (mirrors `sdt purge`).\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { purge, ProjectSource } from '@ddt-tools/core';\n\nexport function purgeCommand(): Command {\n return new Command('purge')\n .description(\n 'Generate a DROP script for every object in the project (bulk teardown). ' +\n 'Requires --confirm-production. Honours all per-type drop gates.',\n )\n .requiredOption('--source <path>', '.ddtproj or .ddtpac to purge from the target.')\n .option(\n '--confirm-production',\n 'Explicit acknowledgement that this drops every project object.',\n false,\n )\n .option('--allow-drop-table', 'Permit DROP TABLE on regular tables (default refuses).', false)\n .option(\n '--allow-unrecoverable-drop',\n 'Permit drops of UNRECOVERABLE types (STREAMING_TABLE/PIPELINE).',\n false,\n )\n .option('--allow-narrowing-types', 'Permit narrowing type changes.', false)\n .option('--allow-table-rebuild', 'Permit table rebuilds.', false)\n .option('-o, --output <path>', 'Write script to a file instead of stdout.')\n .action(async (opts: Record<string, unknown>) => {\n purge.assertPurgeConfirmation({ confirmProduction: opts.confirmProduction === true });\n const sourcePath = path.resolve(String(opts.source));\n const source = new ProjectSource(sourcePath);\n const model = await source.load();\n const result = purge.generatePurgeScript(model, {\n deployOptions: {\n deployment: {\n allowDropTable: opts.allowDropTable === true,\n allowUnrecoverableDrop: opts.allowUnrecoverableDrop === true,\n allowNarrowingTypes: opts.allowNarrowingTypes === true,\n allowTableRebuild: opts.allowTableRebuild === true,\n doNotDropObjectTypes: [],\n preserveTargetOnlyObjects: false,\n blockOnPossibleDataLoss: false,\n },\n },\n targetLabel: 'target (purge)',\n });\n const header =\n `-- PURGE script generated by ddt — drops every object in ${path.basename(sourcePath)} from the target.\\n` +\n `-- ${result.summary.objects} object(s) considered · types: ${result.summary.droppedObjectTypes.join(', ') || '(none)'}\\n` +\n `-- skipped=${result.summary.skipped} refused=${result.summary.refused}\\n\\n`;\n const out = header + result.sql;\n if (opts.output) {\n const outPath = path.resolve(String(opts.output));\n await fs.writeFile(outPath, out, 'utf8');\n console.error(`purge: wrote ${result.summary.objects} object(s) to ${outPath}`);\n } else {\n process.stdout.write(out);\n }\n });\n}\n","/**\n * `ddt preview <fqn>` — DCM compatibility item 3 (mirrors `sdt preview`).\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { preview, createConnection, getProfile } from '@ddt-tools/core';\n\nexport function previewCommand(): Command {\n return new Command('preview')\n .description(\n 'Preview rows from a table (SELECT * FROM <fqn> LIMIT <n>). ' +\n 'Read-only — requires a connection profile.',\n )\n .argument('<fqn>', 'Fully-qualified object name (catalog.schema.table).')\n .requiredOption('--connection <profile>', 'Connection profile to query.')\n .option('--limit <n>', 'Max rows to return. Default 100, max 10000.', '100')\n .option('--where <expr>', 'WHERE clause body (without the WHERE keyword).')\n .option('--format <fmt>', 'Output format: table | json. Default table.', 'table')\n .option('-o, --output <path>', 'Write output to a file instead of stdout.')\n .option('--sql-only', 'Print the SELECT statement without executing it.', false)\n .action(async (fqn: string, opts: Record<string, unknown>) => {\n const limit = Number(opts.limit ?? '100') || 100;\n const where = opts.where ? String(opts.where) : undefined;\n const sql = preview.buildPreviewSql(fqn, { limit, ...(where ? { where } : {}) });\n\n if (opts.sqlOnly === true) {\n process.stdout.write(sql + '\\n');\n return;\n }\n\n const profile = await getProfile(String(opts.connection));\n if (!profile) {\n throw new Error(`Connection profile \"${String(opts.connection)}\" not found.`);\n }\n const conn = createConnection(profile);\n await conn.connect();\n try {\n const result = await preview.previewRows(conn as preview.PreviewRunner, fqn, {\n limit,\n ...(where ? { where } : {}),\n });\n const text =\n String(opts.format ?? 'table').toLowerCase() === 'json'\n ? JSON.stringify(result, null, 2)\n : preview.renderPreviewTable(result);\n if (opts.output) {\n const outPath = path.resolve(String(opts.output));\n await fs.writeFile(outPath, text + '\\n', 'utf8');\n console.error(`preview: wrote ${result.rows.length} row(s) to ${outPath}`);\n } else {\n process.stdout.write(text + '\\n');\n }\n } finally {\n await conn.disconnect();\n }\n });\n}\n","/**\n * `ddt refresh` — DCM compatibility item 4 (mirrors `sdt refresh`).\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { refresh, ProjectSource } from '@ddt-tools/core';\n\nexport function refreshCommand(): Command {\n return new Command('refresh')\n .description(\n 'Generate a REFRESH script for streaming tables + materialized views + pipeline API calls. ' +\n 'Operator runs the output script + makes the pipeline API calls explicitly.',\n )\n .requiredOption('--source <path>', '.ddtproj or .ddtpac defining the objects.')\n .option('--no-streaming-tables', 'Skip REFRESH STREAMING TABLE entries.', false)\n .option('--no-materialized-views', 'Skip REFRESH MATERIALIZED VIEW entries.', false)\n .option('--no-pipelines', 'Skip pipeline API-call comments.', false)\n .option('-o, --output <path>', 'Write script to a file instead of stdout.')\n .action(async (opts: Record<string, unknown>) => {\n const sourcePath = path.resolve(String(opts.source));\n const source = new ProjectSource(sourcePath);\n const model = await source.load();\n const result = refresh.generateRefreshScript(\n model as Parameters<typeof refresh.generateRefreshScript>[0],\n {\n streamingTables: opts.streamingTables !== false,\n materializedViews: opts.materializedViews !== false,\n pipelines: opts.pipelines !== false,\n },\n );\n const header = `-- ${result.summary.streamingTablesRefreshed} streaming table(s) · ${result.summary.materializedViewsRefreshed} materialized view(s) · ${result.summary.pipelinesNoted} pipeline(s)\\n\\n`;\n const out = header + result.sql;\n if (opts.output) {\n const outPath = path.resolve(String(opts.output));\n await fs.writeFile(outPath, out, 'utf8');\n console.error(`refresh: wrote script to ${outPath}`);\n } else {\n process.stdout.write(out);\n }\n });\n}\n","import { rmSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { homedir } from 'node:os';\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { FeatureAdvisor, DDT_HINT_RULES } from '@ddt-tools/core/discovery';\n\nconst IMPORTANT_COMMANDS = [\n 'build',\n 'publish',\n 'compare',\n 'drift',\n 'lint',\n 'extract',\n 'safety',\n 'verify',\n 'validate',\n 'script',\n];\n\nexport function discoverCommand(): Command {\n const cmd = new Command('discover');\n cmd\n .description('Show personalized feature suggestions based on your usage history.')\n .option('--reset', 'Clear usage history and start fresh.')\n .action((opts) => {\n if (opts.reset as boolean) {\n try {\n rmSync(join(homedir(), '.ddt', 'discovery.json'), { force: true });\n } catch {\n /* ignore */\n }\n console.log(chalk.dim(' Discovery history cleared.'));\n return;\n }\n\n const advisor = new FeatureAdvisor('ddt', DDT_HINT_RULES);\n const stats = advisor.getUsageStats();\n const total = Object.values(stats).reduce((a, b) => a + b, 0);\n\n console.log('');\n console.log(chalk.bold(' Feature Discovery') + chalk.dim(' — based on your usage history'));\n console.log('');\n\n if (total === 0) {\n console.log(\n chalk.dim(\n ' No usage recorded yet. Run a few ddt commands to get personalized suggestions.\\n',\n ),\n );\n console.log(chalk.dim(' Quick start:'));\n console.log(` ${chalk.cyan('ddt init')} initialize a new project`);\n console.log(` ${chalk.cyan('ddt build')} build a .ddtpac artifact`);\n console.log(` ${chalk.cyan('ddt compare')} compare project vs. Unity Catalog`);\n console.log('');\n console.log(chalk.dim(' ddt features list · ddt explain <topic>'));\n console.log('');\n return;\n }\n\n const tried = IMPORTANT_COMMANDS.filter((c) => (stats[c] ?? 0) > 0);\n const untried = IMPORTANT_COMMANDS.filter((c) => (stats[c] ?? 0) === 0);\n\n if (tried.length > 0) {\n console.log(chalk.dim(' Commands you use:'));\n const sorted = [...tried].sort((a, b) => (stats[b] ?? 0) - (stats[a] ?? 0));\n for (const c of sorted) {\n console.log(` ${chalk.green('✔')} ddt ${c.padEnd(14)} ${chalk.dim(`${stats[c]}×`)}`);\n }\n console.log('');\n }\n\n if (untried.length > 0) {\n console.log(chalk.dim(' Worth exploring:'));\n for (const c of untried) {\n console.log(` ${chalk.yellow('→')} ${chalk.cyan(`ddt ${c}`)}`);\n }\n console.log('');\n }\n\n console.log(chalk.dim(' ddt features list · ddt explain <topic>\\n'));\n });\n return cmd;\n}\n","/**\n * `ddt find <query>` — search the DDT feature catalog by keyword.\n *\n * DSC.1: surface any DDT capability by describing what you want to do.\n *\n * $ ddt find drift\n * $ ddt find \"multi-team catalog\"\n * $ ddt find compare --limit 3 --format json\n *\n * Reads the same catalog as `ddt features list`. Scoring favors exact\n * id/name/synonym matches over summary body matches. Results include\n * the unlock path so Free users know exactly what each feature needs.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { homedir } from 'node:os';\nimport { Command } from 'commander';\nimport { features as featuresApi, license as licenseApi } from '@ddt-tools/core';\nimport { complete } from '@ddt-tools/core/ai';\nimport chalk from 'chalk';\n\nfunction tierBadge(tier: string): string {\n switch (tier) {\n case 'free':\n return chalk.green('Free');\n case 'pro':\n return chalk.cyan('Pro');\n case 'team':\n return chalk.yellow('Team');\n case 'enterprise':\n return chalk.magenta('Enterprise');\n default:\n return tier;\n }\n}\n\nexport function findCommand(): Command {\n const cmd = new Command('find');\n cmd\n .description('Search DDT features by keyword — find what you want to do.')\n .argument('<query...>', 'Keywords to search for (e.g. \"drift detection\", \"multi-team\").')\n .option('-n, --limit <n>', 'Max results to show.', '5')\n .option('--format <fmt>', 'Output format: text | json.', 'text')\n .option('--tier <tier>', 'Filter by tier: free | pro | team | enterprise.')\n .option('--shipped', 'Only include shipped features (exclude roadmap).')\n .option(\n '--ai',\n 'DSC.4: escalate to the configured AI provider when deterministic search yields low-confidence hits. Costs tokens; default off.',\n )\n .option(\n '--ai-threshold <n>',\n 'Confidence below which --ai triggers escalation (0..1, default 0.55).',\n '0.55',\n )\n .option(\n '--no-ai-cache',\n 'DSC.4-followup: skip the on-disk intent cache and always re-query the AI provider when --ai escalates.',\n )\n .action(async (queryParts: string[], opts) => {\n const query = queryParts.join(' ').trim();\n const limit = Math.max(1, parseInt(String(opts.limit), 10) || 5);\n const fmt = String(opts.format ?? 'text').toLowerCase();\n const tierFilter = opts.tier as 'free' | 'pro' | 'team' | 'enterprise' | undefined;\n const statusFilter = opts.shipped ? ('shipped' as const) : undefined;\n\n const licenseObj = await licenseApi.loadLicense();\n let hits: ReturnType<typeof featuresApi.searchFeatures> = [];\n let stage: 1 | 2 = 1;\n let tokensUsed = 0;\n let cacheHit = false;\n if (opts.ai) {\n const threshold = Math.max(0, Math.min(1, Number(opts.aiThreshold ?? '0.55')));\n const cachePath = path.join(homedir(), '.ddt', 'intent-cache.json');\n const useCache = opts.aiCache !== false;\n let cache = featuresApi.emptyIntentCache();\n if (useCache) {\n try {\n const body = await fs.readFile(cachePath, 'utf8');\n cache = featuresApi.parseIntentCache(body);\n } catch {\n // No cache yet.\n }\n const cached = featuresApi.lookupIntent(cache, query);\n if (cached) {\n const idSet = new Set(cached.featureIds);\n const matchedFeatures = featuresApi.DDT_FEATURE_CATALOG.filter((f) =>\n idSet.has(f.id),\n ).sort((a, b) => cached.featureIds.indexOf(a.id) - cached.featureIds.indexOf(b.id));\n hits = matchedFeatures.slice(0, limit).map((f) => ({\n feature: f,\n score: 1.0,\n matchedFields: ['ai-intent-cached'],\n }));\n stage = 2;\n tokensUsed = 0;\n cacheHit = true;\n }\n }\n if (!cacheHit) {\n const result = await featuresApi.intentMatch(\n query,\n featuresApi.DDT_FEATURE_CATALOG,\n { limit, tier: tierFilter, status: statusFilter, threshold },\n (messages) => complete(messages, { feature: 'find.intent' }),\n );\n hits = [...result.hits];\n stage = result.stage;\n tokensUsed = result.tokensUsed;\n if (useCache && stage === 2 && hits.length > 0) {\n const next = featuresApi.evictExpiredIntents(\n featuresApi.addIntent(\n cache,\n query,\n hits.map((h) => h.feature.id),\n tokensUsed,\n ),\n );\n try {\n await fs.mkdir(path.dirname(cachePath), { recursive: true });\n await fs.writeFile(cachePath, featuresApi.serializeIntentCache(next), 'utf8');\n } catch {\n // Best-effort.\n }\n }\n }\n } else {\n hits = featuresApi.searchFeatures(query, featuresApi.DDT_FEATURE_CATALOG, {\n limit,\n tier: tierFilter,\n status: statusFilter,\n });\n }\n\n if (fmt === 'json') {\n process.stdout.write(\n JSON.stringify(\n hits.map((h) => ({\n id: h.feature.id,\n name: h.feature.name,\n tier: h.feature.tier,\n status: h.feature.status,\n score: h.score,\n matchedFields: h.matchedFields,\n summary: h.feature.summary,\n unlockHow: h.feature.unlockHow,\n useCases: h.feature.useCases,\n relatedFeatures: h.feature.relatedFeatures,\n })),\n null,\n 2,\n ) + '\\n',\n );\n return;\n }\n\n if (hits.length === 0) {\n process.stdout.write(\n chalk.dim(` No features found for \"${query}\".\\n`) +\n chalk.dim(` Try: ddt features list · ddt explain <topic>\\n`),\n );\n return;\n }\n\n process.stdout.write('\\n');\n for (const hit of hits) {\n const avail = featuresApi.isFeatureAvailable(hit.feature, licenseObj);\n const statusMark =\n hit.feature.status === 'roadmap'\n ? chalk.dim('🚧 roadmap')\n : avail\n ? chalk.green('✅ available')\n : chalk.dim('🔒 locked');\n\n process.stdout.write(\n ` ${chalk.bold(hit.feature.name)} ${tierBadge(hit.feature.tier)} ${statusMark}\\n` +\n ` ${chalk.dim(hit.feature.summary)}\\n`,\n );\n if (hit.feature.useCases && hit.feature.useCases.length > 0) {\n process.stdout.write(chalk.dim(` Use when: ${hit.feature.useCases[0]}\\n`));\n }\n if (!avail && hit.feature.status === 'shipped') {\n process.stdout.write(chalk.dim(` Unlock: ${hit.feature.unlockHow}\\n`));\n }\n if (hit.feature.surfaces && hit.feature.surfaces.length > 0) {\n process.stdout.write(\n chalk.dim(` Surface: ${hit.feature.surfaces.slice(0, 2).join(', ')}\\n`),\n );\n }\n process.stdout.write(chalk.dim(` ddt features show ${hit.feature.id}\\n\\n`));\n }\n\n const aiNote =\n stage === 2\n ? cacheHit\n ? ' (AI-cached, 0 tokens)'\n : ` (AI-escalated, ${tokensUsed} tokens)`\n : '';\n process.stdout.write(\n chalk.dim(\n ` ${hits.length} result${hits.length === 1 ? '' : 's'} for \"${query}\"${aiNote}. `,\n ) + chalk.dim('ddt features list · ddt features show <id>\\n'),\n );\n });\n return cmd;\n}\n","/**\n * `ddt scan-secrets` — scan a project's DDL bodies for hardcoded credentials.\n *\n * Covers: Databricks PATs (dapi*), workspace URLs with embedded tokens,\n * OAuth client_secret literals, AWS keys, OpenAI keys, GitHub tokens,\n * Slack tokens, JWTs, PEM private-key blocks, and generic credential fields.\n *\n * Exit codes:\n * 0 — clean (or only warnings in non-strict mode)\n * 1 — errors found (always) or any finding in --strict mode\n *\n * Mirrors `sdt scan-secrets`.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { loadProject, pac, parseProjectModel, secretScanner } from '@ddt-tools/core';\n\nexport function scanSecretsCommand(): Command {\n const cmd = new Command('scan-secrets');\n cmd\n .description('Scan a project or pac for hardcoded credentials in DDL bodies.')\n .requiredOption('--source <path>', '.ddtproj or .ddtpac to scan.')\n .option(\n '--strict',\n 'Exit 1 on any finding (errors or warnings). Default: exit 1 on errors only.',\n false,\n )\n .option('--format <fmt>', 'table | json | markdown. Default table.', 'table')\n .option('-o, --out <path>', 'Output file path. Defaults to stdout.')\n .action(async (opts: { source: string; strict?: boolean; format?: string; out?: string }) => {\n const sourcePath = String(opts.source);\n const model = await loadModel(sourcePath);\n const result = secretScanner.scanSecrets(model, { strict: opts.strict });\n\n const fmt = (opts.format ?? 'table').toLowerCase();\n let payload: string;\n if (fmt === 'json') {\n payload = JSON.stringify(result, null, 2);\n } else if (fmt === 'markdown') {\n payload = secretScanner.formatSecretReportMarkdown(result);\n } else {\n payload = secretScanner.formatSecretReport(result);\n }\n\n if (opts.out) {\n const out = path.resolve(String(opts.out));\n await fs.mkdir(path.dirname(out), { recursive: true });\n await fs.writeFile(out, payload + (payload.endsWith('\\n') ? '' : '\\n'), 'utf8');\n console.error(\n `Wrote ${out} (${result.findings.length} finding(s): ${result.errorCount} error(s), ${result.warningCount} warning(s)).`,\n );\n } else {\n process.stdout.write(payload + (payload.endsWith('\\n') ? '' : '\\n'));\n }\n\n if (result.errorCount > 0 || (opts.strict && result.findings.length > 0)) {\n process.exitCode = 1;\n }\n });\n\n return cmd;\n}\n\nasync function loadModel(sourcePath: string) {\n if (sourcePath.endsWith('.ddtpac')) {\n const c = await pac.readPac(sourcePath);\n return c.model;\n }\n const loaded = await loadProject(sourcePath);\n return await parseProjectModel(loaded);\n}\n","/**\n * `ddt error-lookup` — look up a failure in the known-error catalog (DSR.2).\n *\n * Usage:\n * ddt error-lookup --code PERMISSION_DENIED\n * ddt error-lookup --fingerprint abcd1234deadbeef\n * ddt error-lookup --message \"Permission denied\"\n * ddt error-lookup --list\n *\n * Exit codes:\n * 0 — match found, or `--list` ran\n * 1 — no match found for the supplied input\n * 2 — usage error (no --code / --fingerprint / --message / --list passed)\n *\n * Mirrors `sdt error-lookup`.\n */\nimport { Command } from 'commander';\nimport { errorCatalog } from '@ddt-tools/core';\n\nexport function errorLookupCommand(): Command {\n const cmd = new Command('error-lookup');\n cmd\n .description('Look up a failure in the known-error catalog by code, fingerprint, or message.')\n .option('--code <code>', 'Adapter error code (e.g. PERMISSION_DENIED).')\n .option('--fingerprint <hex>', '16-char fingerprint from a prior failure.')\n .option('--message <text>', 'Free-text error message — falls back to regex match.')\n .option('--list', 'List every entry in the catalog (with code/key/cause).', false)\n .option('--format <fmt>', 'text | json. Default text.', 'text')\n .action(\n (opts: {\n code?: string;\n fingerprint?: string;\n message?: string;\n list?: boolean;\n format?: string;\n }) => {\n const fmt = (opts.format ?? 'text').toLowerCase();\n if (opts.list) {\n const all = errorCatalog.DEFAULT_KNOWN_ERRORS;\n if (fmt === 'json') {\n process.stdout.write(JSON.stringify(all, null, 2) + '\\n');\n } else {\n for (const entry of all) {\n const codeList = entry.codes?.join(', ') ?? '—';\n process.stdout.write(\n `${entry.key}\\n codes: ${codeList}\\n cause: ${entry.causeSummary}\\n\\n`,\n );\n }\n }\n return;\n }\n if (!opts.code && !opts.fingerprint && !opts.message) {\n process.stderr.write('error-lookup: pass --code, --fingerprint, --message, or --list\\n');\n process.exitCode = 2;\n return;\n }\n const match = errorCatalog.lookupKnownError({\n code: opts.code,\n fingerprint: opts.fingerprint,\n message: opts.message,\n });\n if (!match) {\n process.stderr.write('No catalog entry matched.\\n');\n process.exitCode = 1;\n return;\n }\n if (fmt === 'json') {\n process.stdout.write(JSON.stringify(match, null, 2) + '\\n');\n } else {\n process.stdout.write(errorCatalog.formatCatalogMatch(match) + '\\n');\n }\n },\n );\n return cmd;\n}\n","/**\n * `ddt deploy-status` — inspect resumable deploy checkpoints (DSR.3).\n *\n * Usage:\n * ddt deploy-status # list every resumable deploy\n * ddt deploy-status <deployId> # show one checkpoint\n * ddt deploy-status <deployId> --remove # delete a checkpoint\n * ddt deploy-status --format json # machine-readable list\n *\n * Mirrors `sdt deploy-status`.\n */\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { deployCheckpoint } from '@ddt-tools/core';\n\nconst DEFAULT_STATE_DIR = path.join(process.cwd(), deployCheckpoint.DEFAULT_STATE_DIR_REL);\n\nexport function deployStatusCommand(): Command {\n const cmd = new Command('deploy-status');\n cmd\n .description('Show or list resumable deploy checkpoints written by `ddt publish`.')\n .argument('[deployId]', 'Deploy id to inspect. Omit to list every checkpoint.')\n .option('--state-dir <path>', 'Directory containing checkpoint JSON files.', DEFAULT_STATE_DIR)\n .option('--remove', 'Delete the checkpoint (after status display). Requires <deployId>.', false)\n .option('--format <fmt>', 'text | json. Default text.', 'text')\n .action(\n async (\n deployId: string | undefined,\n opts: { stateDir: string; remove?: boolean; format?: string },\n ) => {\n const stateDir = path.resolve(opts.stateDir);\n const fmt = (opts.format ?? 'text').toLowerCase();\n if (!deployId) {\n const list = await deployCheckpoint.listCheckpoints(stateDir);\n if (fmt === 'json') {\n process.stdout.write(JSON.stringify(list, null, 2) + '\\n');\n return;\n }\n if (list.length === 0) {\n process.stdout.write('No resumable deploys.\\n');\n return;\n }\n for (const item of list) {\n process.stdout.write(\n `${item.deployId} ${item.state} ${item.completedSteps}/${item.totalSteps} steps profile=${item.profile}${item.env ? ` env=${item.env}` : ''} updated=${item.lastUpdatedAt}\\n`,\n );\n }\n return;\n }\n const state = await deployCheckpoint.loadCheckpoint(stateDir, deployId);\n if (!state) {\n process.stderr.write(\n `No checkpoint found for deploy id ${JSON.stringify(deployId)} under ${stateDir}.\\n`,\n );\n process.exitCode = 1;\n return;\n }\n if (fmt === 'json') {\n process.stdout.write(JSON.stringify(state, null, 2) + '\\n');\n } else {\n process.stdout.write(deployCheckpoint.formatCheckpointStatus(state) + '\\n');\n }\n if (opts.remove) {\n await deployCheckpoint.removeCheckpoint(stateDir, deployId);\n process.stderr.write(`Removed checkpoint ${deployId}.\\n`);\n }\n },\n );\n return cmd;\n}\n","/**\n * `ddt approval-chain` — M-of-N signed approval workflow (DSR.8).\n *\n * Subcommands: keygen / sign / verify. Mirrors `sdt approval-chain`.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport type * as nodeCrypto from 'node:crypto';\nimport { Command } from 'commander';\nimport { approvalChain } from '@ddt-tools/core';\n\nexport function approvalChainCommand(): Command {\n const cmd = new Command('approval-chain');\n cmd.description('Signed M-of-N approval workflow (DSR.8).');\n cmd.addCommand(keygenCommand());\n cmd.addCommand(signCommand());\n cmd.addCommand(verifyCommand());\n return cmd;\n}\n\nfunction keygenCommand(): Command {\n const c = new Command('keygen');\n c.description('Generate an Ed25519 keypair for an approver.')\n .requiredOption('--id <approver>', 'Approver id (used as the filename stem).')\n .requiredOption('--out <dir>', 'Output directory for the keypair.')\n .action(async (opts: { id: string; out: string }) => {\n const dir = path.resolve(opts.out);\n await fs.mkdir(dir, { recursive: true });\n const pair = approvalChain.generateApproverKeyPair();\n const priv = path.join(dir, `${opts.id}.pem`);\n const pub = path.join(dir, `${opts.id}.pub.pem`);\n await fs.writeFile(priv, pair.privateKeyPem, { mode: 0o600 });\n await fs.writeFile(pub, pair.publicKeyPem);\n process.stdout.write(`Wrote ${priv} and ${pub} (kid=${pair.kid}).\\n`);\n });\n return c;\n}\n\nfunction signCommand(): Command {\n const c = new Command('sign');\n c.description('Produce a signed approval record.')\n .requiredOption('--deploy-id <id>', 'Stable deploy id.')\n .requiredOption('--env <env>', 'Target environment (matches a key in approval.json).')\n .requiredOption('--approver <id>', \"Approver id (must appear in the env's approvers list).\")\n .requiredOption('--decision <decision>', 'approve | reject', 'approve')\n .requiredOption('--key <path>', \"Path to the approver's private key (PEM).\")\n .option('--digest <hex>', 'Optional compare+safety digest the approver reviewed.')\n .option('--out <path>', 'Write the signed record JSON to this path (default stdout).')\n .action(\n async (opts: {\n deployId: string;\n env: string;\n approver: string;\n decision: string;\n key: string;\n digest?: string;\n out?: string;\n }) => {\n const decision = (opts.decision === 'reject' ? 'reject' : 'approve') as\n | 'approve'\n | 'reject';\n const privateKeyPem = await fs.readFile(path.resolve(opts.key), 'utf8');\n const kid = approvalChain.publicKeyKid(\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n (require('node:crypto') as typeof nodeCrypto)\n .createPublicKey(privateKeyPem)\n .export({ format: 'pem', type: 'spki' })\n .toString(),\n );\n const record = approvalChain.signApprovalRecord(\n {\n deployId: opts.deployId,\n env: opts.env,\n approver: opts.approver,\n decision,\n ts: new Date().toISOString(),\n digest: opts.digest,\n },\n privateKeyPem,\n { kid },\n );\n const payload = JSON.stringify(record, null, 2) + '\\n';\n if (opts.out) {\n await fs.mkdir(path.dirname(path.resolve(opts.out)), { recursive: true });\n await fs.writeFile(path.resolve(opts.out), payload);\n process.stderr.write(`Wrote ${opts.out}\\n`);\n } else {\n process.stdout.write(payload);\n }\n },\n );\n return c;\n}\n\nfunction verifyCommand(): Command {\n const c = new Command('verify');\n c.description('Evaluate the signed chain against the env policy.')\n .requiredOption('--deploy-id <id>', 'Stable deploy id.')\n .requiredOption('--env <env>', 'Target environment.')\n .requiredOption('--config <path>', 'Path to approval.json.')\n .requiredOption('--records <path>', 'Path to JSON file containing a SignedApprovalRecord[].')\n .option('--digest <hex>', 'Optional live compare+safety digest.')\n .option('--format <fmt>', 'text | json. Default text.', 'text')\n .action(\n async (opts: {\n deployId: string;\n env: string;\n config: string;\n records: string;\n digest?: string;\n format?: string;\n }) => {\n const configPath = path.resolve(opts.config);\n const config = await approvalChain.loadApprovalChainConfig(configPath);\n if (!config) {\n process.stderr.write(`Config file not found: ${configPath}\\n`);\n process.exitCode = 1;\n return;\n }\n const records = JSON.parse(\n await fs.readFile(path.resolve(opts.records), 'utf8'),\n ) as approvalChain.SignedApprovalRecord[];\n const registry = approvalChain.resolveRegistry(config, configPath);\n const outcome = await approvalChain.evaluateApprovalChain({\n deployId: opts.deployId,\n env: opts.env,\n currentDigest: opts.digest,\n records,\n config,\n registry,\n });\n if ((opts.format ?? 'text').toLowerCase() === 'json') {\n process.stdout.write(JSON.stringify(outcome, null, 2) + '\\n');\n } else {\n process.stdout.write(\n `${outcome.satisfied ? 'OK' : 'BLOCKED'}: ${outcome.satisfiedBy.length} valid / ${outcome.missingCount} missing\\n`,\n );\n if (outcome.satisfiedBy.length > 0)\n process.stdout.write(` approvers: ${outcome.satisfiedBy.join(', ')}\\n`);\n if (outcome.ignored.length > 0)\n process.stdout.write(\n ` ignored: ${outcome.ignored.map((i) => `${i.approver}=${i.reason}`).join(', ')}\\n`,\n );\n if (outcome.blockReason) process.stdout.write(` ${outcome.blockReason}\\n`);\n }\n if (!outcome.satisfied) process.exitCode = 1;\n },\n );\n return c;\n}\n","/**\n * `ddt standards` — team SQL standards commands.\n *\n * Subcommands:\n * init — scaffold a starter `.ddt/standards.json` config\n * check — check SQL files against team standards (STD.6)\n * list-rules — list every rule the checker knows (STD.6)\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { standards } from '@ddt-tools/core';\n\nexport function standardsCommand(): Command {\n const cmd = new Command('standards');\n cmd.description('Team SQL standards — init, check, fix, and explain.');\n\n cmd.addCommand(initSubcommand());\n cmd.addCommand(checkSubcommand());\n cmd.addCommand(listRulesSubcommand());\n\n return cmd;\n}\n\n// ─────────────────────────────────────────────────────────────────────\n// `ddt standards init`\n// ─────────────────────────────────────────────────────────────────────\n\nfunction initSubcommand(): Command {\n const init = new Command('init');\n init\n .description(\n 'Scaffold a starter .ddt/standards.json config with sensible defaults. ' +\n 'Edit the file to match your team conventions, then run `ddt standards check`.',\n )\n .option(\n '--dir <path>',\n 'Project root directory containing or to receive .ddt/. Defaults to current directory.',\n )\n .option('--force', 'Overwrite an existing standards.json without prompting.')\n .option(\n '--preset <name>',\n 'Starter preset: \"default\" (Databricks-flavored team conventions) | \"dbt\" (dbt-community conventions — stg_/int_/fct_/dim_ prefixes + lower keyword case + dbtMode: \"on\").',\n 'default',\n )\n .action(async (opts: { dir?: string; force?: boolean; preset?: string }) => {\n const projectRoot = path.resolve(String(opts.dir ?? '.'));\n const ddtDir = path.join(projectRoot, '.ddt');\n const configPath = path.join(ddtDir, 'standards.json');\n\n // DBTC.5 — preset selector validates here so an unknown name fails\n // fast (and not later as a runtime schema error).\n const presetName = String(opts.preset ?? 'default').toLowerCase();\n if (presetName !== 'default' && presetName !== 'dbt') {\n console.error(`Unknown --preset: ${opts.preset}. Use \"default\" or \"dbt\".`);\n process.exit(1);\n return;\n }\n const preset = presetName as standards.StandardsPreset;\n\n await fs.mkdir(ddtDir, { recursive: true });\n\n if (!opts.force) {\n try {\n await fs.access(configPath);\n console.error(\n `standards.json already exists at ${configPath}.\\n` + `Pass --force to overwrite.`,\n );\n process.exit(1);\n } catch {\n // file doesn't exist — proceed\n }\n }\n\n const content = standards.scaffoldStandardsConfig(preset);\n await fs.writeFile(configPath, content, 'utf8');\n console.log(`✅ Created ${configPath}${preset !== 'default' ? ` (${preset} preset)` : ''}`);\n console.log('');\n console.log('Edit the file to match your team conventions:');\n console.log(' • naming.tablePrefixes — required table name prefixes (e.g. dim_, fct_)');\n console.log(' • naming.caseStyle — snake_case | UPPER_CASE | camelCase | none');\n console.log(' • structure.mandatoryColumns — columns every table must include');\n console.log(' • content.noSelectStar — ban SELECT * in views');\n console.log('');\n console.log('Mode values: warn | error | enforce | autofix | autofix-silent | off');\n console.log('Then run `ddt standards check` to lint your SQL surface.');\n });\n return init;\n}\n\n// ─────────────────────────────────────────────────────────────────────\n// `ddt standards check`\n// ─────────────────────────────────────────────────────────────────────\n\nfunction checkSubcommand(): Command {\n const check = new Command('check');\n check\n .description(\n 'Check SQL files against the team standards config. Without --fix this is a read-only lint pass; with --fix it rewrites files for deterministic violations (sql-format.keyword-case). Use --ai-fix to route ambiguous violations through the configured AI provider.',\n )\n .argument('[paths...]', 'SQL files or directories to check (defaults to project root)')\n .option(\n '--dir <path>',\n 'Project root containing .ddt/standards.json. Defaults to current directory.',\n )\n .option(\n '--fix',\n 'Apply autofixes (sql-format.keyword-case today; opt-in per-rule via standards.json mode = autofix or autofix-silent).',\n )\n .option(\n '--ai-fix',\n 'Suggest fixes via the configured AI provider for non-autofixable findings.',\n )\n .option(\n '--explain <rule>',\n 'Print the deep explanation for a single rule (e.g. naming.case-style).',\n )\n .option('--json', 'Emit findings as JSON instead of human-readable text.')\n .option(\n '--dbt',\n 'Force dbt-mode on: pre-mask {{ ... }} / {% ... %} Jinja blocks before running the four family checkers. Default: auto-detect.',\n )\n .option(\n '--no-dbt',\n 'Force dbt-mode off: feed Jinja text directly to the checkers (almost always wrong on dbt models).',\n )\n .action(\n async (\n paths: string[],\n opts: {\n dir?: string;\n fix?: boolean;\n aiFix?: boolean;\n explain?: string;\n json?: boolean;\n dbt?: boolean;\n },\n ) => {\n // --explain is a stand-alone diagnostic mode — short-circuit before any I/O.\n if (opts.explain) {\n const body = standards.formatRuleExplanation(opts.explain);\n if (!body) {\n console.error(\n `Unknown rule: ${opts.explain}. Run \\`ddt standards list-rules\\` for the full list.`,\n );\n process.exit(2);\n return;\n }\n console.log(body);\n return;\n }\n\n const projectRoot = path.resolve(String(opts.dir ?? '.'));\n const loadedConfig = await standards.loadStandards(projectRoot);\n if (!loadedConfig) {\n console.error(\n `No standards config found at ${path.join(projectRoot, standards.STANDARDS_CONFIG_FILENAME)}. Run \\`ddt standards init\\` first.`,\n );\n process.exit(2);\n return;\n }\n // DBTC.4 — --dbt / --no-dbt overrides config.dbtMode when present.\n const config =\n opts.dbt === true\n ? { ...loadedConfig, dbtMode: 'on' as const }\n : opts.dbt === false\n ? { ...loadedConfig, dbtMode: 'off' as const }\n : loadedConfig;\n\n const targets = paths.length > 0 ? paths : [projectRoot];\n const files = await collectSqlFiles(targets);\n if (files.length === 0) {\n console.error('No .sql files matched the given paths.');\n process.exit(2);\n return;\n }\n\n const readFiles = await Promise.all(\n files.map(async (filePath) => ({\n filePath: path.relative(projectRoot, filePath),\n sql: await fs.readFile(filePath, 'utf8'),\n })),\n );\n\n if (opts.fix) {\n const fixResults = standards.runMultiFileFix(readFiles, config);\n // Write rewritten files back, mapping the relative path back to absolute.\n await Promise.all(\n fixResults.map(async (r) => {\n if (!r.changed) return;\n const absolute = path.resolve(projectRoot, r.filePath);\n await fs.writeFile(absolute, r.result.fixedSql, 'utf8');\n }),\n );\n if (opts.json) {\n console.log(JSON.stringify(fixResults, null, 2));\n } else {\n console.log(standards.formatFixReport(fixResults));\n }\n // Exit non-zero if any non-autofixable findings remain — CI catches them.\n const stillBroken = fixResults.some((r) => r.result.remainingFindings.length > 0);\n process.exit(stillBroken ? 1 : 0);\n return;\n }\n\n const result = standards.runMultiFileCheck(readFiles, config);\n if (opts.aiFix) {\n await runAiFix(result, config, projectRoot);\n return;\n }\n\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.log(standards.formatCheckReport(result));\n }\n process.exit(result.blockingFiles > 0 ? 1 : 0);\n },\n );\n return check;\n}\n\nasync function runAiFix(\n result: {\n files: Array<{\n filePath: string;\n findings: Array<{\n rule: string;\n severity: string;\n message: string;\n line?: number;\n identifier?: string;\n suggestion?: string;\n family: string;\n autofix?: boolean;\n }>;\n }>;\n },\n config: Awaited<ReturnType<typeof standards.loadStandards>>,\n projectRoot: string,\n): Promise<void> {\n if (!config) return;\n const standardsCtx = standards.serializeStandardsContext({\n naming: config.naming,\n structure: config.structure,\n sqlFormat: config.sqlFormat,\n content: config.content,\n });\n let suggested = 0;\n for (const file of result.files) {\n for (const finding of file.findings) {\n if (finding.severity !== 'error' && finding.severity !== 'warning') continue;\n const absolute = path.resolve(projectRoot, file.filePath);\n const sql = await fs.readFile(absolute, 'utf8');\n try {\n const fix = await standards.aiFixStandard({\n snippet: sql,\n finding: finding as unknown as Parameters<typeof standards.aiFixStandard>[0]['finding'],\n standardsContext: standardsCtx,\n });\n console.log(`\\n${file.filePath} — ${finding.rule}:`);\n console.log(\n ` Suggested rewrite (tokens used: ${fix.usage.promptTokens}p + ${fix.usage.completionTokens}c):`,\n );\n console.log(fix.rewrittenSnippet.replace(/^/gm, ' '));\n if (fix.explanation) {\n console.log(` Explanation: ${fix.explanation}`);\n }\n suggested++;\n } catch (err: unknown) {\n console.error(` AI-fix failed: ${(err as Error).message ?? String(err)}`);\n }\n }\n }\n console.log(`\\n${suggested} AI suggestion(s) generated. Apply manually after review.`);\n}\n\n// ─────────────────────────────────────────────────────────────────────\n// `ddt standards list-rules`\n// ─────────────────────────────────────────────────────────────────────\n\nfunction listRulesSubcommand(): Command {\n const list = new Command('list-rules');\n list\n .description('List every standards rule the checker knows about, with auto-fix capability.')\n .action(() => {\n console.log(standards.formatRuleList());\n });\n return list;\n}\n\n// ─────────────────────────────────────────────────────────────────────\n// Helpers\n// ─────────────────────────────────────────────────────────────────────\n\nasync function collectSqlFiles(paths: ReadonlyArray<string>): Promise<string[]> {\n const out: string[] = [];\n for (const p of paths) {\n const abs = path.resolve(p);\n try {\n const stat = await fs.stat(abs);\n if (stat.isFile() && abs.endsWith('.sql')) {\n out.push(abs);\n } else if (stat.isDirectory()) {\n await walkDirectory(abs, out);\n }\n } catch {\n // Skip non-existent paths silently — the CLI's \"no files matched\"\n // message covers the empty case.\n }\n }\n return out;\n}\n\nasync function walkDirectory(dir: string, accumulator: string[]): Promise<void> {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const e of entries) {\n if (e.name.startsWith('.') || e.name === 'node_modules') continue;\n const child = path.join(dir, e.name);\n if (e.isDirectory()) {\n await walkDirectory(child, accumulator);\n } else if (e.isFile() && e.name.endsWith('.sql')) {\n accumulator.push(child);\n }\n }\n}\n","/**\n * `ddt perf` — CLI performance diagnostics + recommendations.\n *\n * Subcommands:\n * - `cold-start` (RES.5): CLI startup latency vs the 200ms budget.\n * - `unused` (PERF.6): given a project model + query-history snapshot,\n * identify objects unreferenced for ≥ N days.\n *\n * Mirrors `Snowflake/packages/cli/src/commands/perf.ts`.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\n// Subpath import, NOT the `@ddt-tools/core` barrel — keeps `ddt perf cold-start`\n// itself off the all-modules import path it exists to measure (RH3.3).\nimport { loadProject, parseProjectModel } from '@ddt-tools/core/project';\nimport {\n findMaterializedViewCandidates,\n findUnusedObjects,\n recommendWarehouseSize,\n renderMvCandidatesMarkdown,\n renderUnusedObjectsMarkdown,\n renderWarehouseSizingMarkdown,\n} from '@ddt-tools/core/perf';\nimport type { QueryHistoryEntry } from '@ddt-tools/core/queryHistory';\n\nconst COLD_START_BUDGET_MS = 200;\n\nexport function perfCommand(): Command {\n const cmd = new Command('perf');\n cmd.description('CLI performance diagnostics (cold-start audit, hot-path profiling).');\n\n const coldStart = new Command('cold-start');\n coldStart\n .description('Measure CLI cold-start latency and compare against the 200ms budget.')\n .option('--json', 'Emit JSON instead of human-readable output.', false)\n .option(\n '--budget <ms>',\n 'Override the pass/fail threshold in ms.',\n String(COLD_START_BUDGET_MS),\n )\n .action((opts) => {\n const startNs: bigint | undefined = (globalThis as { __DDT_START_NS__?: bigint })\n .__DDT_START_NS__;\n const nowNs = process.hrtime.bigint();\n const budgetMs = Number(opts.budget ?? COLD_START_BUDGET_MS);\n\n let elapsedMs: number | null = null;\n if (startNs !== undefined) {\n elapsedMs = Number(nowNs - startNs) / 1e6;\n }\n\n const pass = elapsedMs !== null && elapsedMs <= budgetMs;\n const note =\n elapsedMs === null\n ? 'Start timestamp not recorded — add `globalThis.__DDT_START_NS__ = process.hrtime.bigint()` to the CLI entry point.'\n : pass\n ? `✓ ${elapsedMs.toFixed(1)} ms ≤ ${budgetMs} ms budget`\n : `✗ ${elapsedMs.toFixed(1)} ms > ${budgetMs} ms budget — see docs/CONTRIBUTING.md for lazy-load patterns`;\n\n if (opts.json) {\n process.stdout.write(JSON.stringify({ elapsedMs, budgetMs, pass, note }, null, 2) + '\\n');\n } else {\n console.log(`ddt cold-start: ${note}`);\n if (elapsedMs !== null) {\n const bar = '█'.repeat(Math.min(40, Math.round((elapsedMs / budgetMs) * 40)));\n const pct = ((elapsedMs / budgetMs) * 100).toFixed(0);\n console.log(` ${bar} ${pct}% of ${budgetMs}ms budget`);\n }\n }\n process.exitCode = pass ? 0 : 1;\n });\n\n cmd.addCommand(coldStart);\n\n const unused = new Command('unused');\n unused\n .description(\n 'Find project objects unreferenced for ≥ --threshold-days in a query-history snapshot (PERF.6). ' +\n 'Offline — feeds a JSON array of QueryHistoryEntry via --history-file.',\n )\n .requiredOption('-p, --project <path>', 'Path to the .ddtproj file.')\n .requiredOption(\n '--history-file <path>',\n 'Path to a JSON file containing a QueryHistoryEntry[] (e.g. saved from `ddt history --last 1000 --format json`).',\n )\n .option('--threshold-days <n>', 'Days-of-inactivity cutoff (default 30).', '30')\n .option(\n '--reference-date <iso>',\n 'ISO-8601 timestamp used as \"now\" (default: most recent entry).',\n )\n .option('--format <fmt>', 'Output format: text | json. Default text.', 'text')\n .option('-o, --out <path>', 'Write report to a file instead of stdout.')\n .action(async (opts) => {\n const loaded = await loadProject(String(opts.project));\n const model = await parseProjectModel(loaded);\n const testable = new Set<string>([\n 'TABLE',\n 'MANAGED_TABLE',\n 'EXTERNAL_TABLE',\n 'VIEW',\n 'MATERIALIZED_VIEW',\n 'STREAMING_TABLE',\n ]);\n const fqns: string[] = [];\n for (const obj of model) {\n if (!testable.has(obj.objectType)) continue;\n const cat = obj.fqn.database;\n const sc = obj.fqn.schema;\n if (!cat || !sc) continue;\n fqns.push(`${cat}.${sc}.${obj.fqn.name}`);\n }\n const historyAbs = path.resolve(String(opts.historyFile));\n const historyRaw = await fs.readFile(historyAbs, 'utf8');\n const entries = JSON.parse(historyRaw) as QueryHistoryEntry[];\n if (!Array.isArray(entries)) {\n throw new Error(\n `--history-file ${historyAbs} did not parse to an array of QueryHistoryEntry.`,\n );\n }\n const thresholdDays = Number(opts.thresholdDays ?? '30');\n const report = findUnusedObjects(entries, fqns, {\n thresholdDays,\n referenceDate: opts.referenceDate ? String(opts.referenceDate) : undefined,\n });\n const output =\n String(opts.format).toLowerCase() === 'json'\n ? JSON.stringify(report, null, 2)\n : renderUnusedObjectsMarkdown(report);\n if (opts.out) {\n const out = path.resolve(String(opts.out));\n await fs.mkdir(path.dirname(out), { recursive: true });\n await fs.writeFile(out, output, 'utf8');\n console.error(\n `Wrote ${out} — ${report.unusedCount}/${report.totalObjects} object(s) unreferenced ≥ ${thresholdDays}d.`,\n );\n } else {\n process.stdout.write(output + '\\n');\n }\n });\n cmd.addCommand(unused);\n\n const mvCandidates = new Command('mv-candidates');\n mvCandidates\n .description(\n 'Identify recurring SELECT shapes that may benefit from caching as a materialized view (PERF.4). ' +\n 'Offline — feeds a JSON array of QueryHistoryEntry via --history-file. Suggests CREATE MATERIALIZED VIEW DDL.',\n )\n .requiredOption(\n '--history-file <path>',\n 'Path to a JSON file containing a QueryHistoryEntry[] (e.g. saved from `ddt history --last 1000 --format json`).',\n )\n .option('--threshold-runs <n>', 'Min run count to qualify as a candidate (default 5).', '5')\n .option(\n '--threshold-total-ms <n>',\n 'Min sum of durationMs across runs to qualify (default 60000).',\n '60000',\n )\n .option('--top-n <n>', 'Cap on candidates returned (default 25).', '25')\n .option('--mv-schema <name>', 'Schema to prefix on the suggested MV name (e.g. `analytics`).')\n .option('--format <fmt>', 'Output format: text | json. Default text.', 'text')\n .option('-o, --out <path>', 'Write report to a file instead of stdout.')\n .action(async (opts) => {\n const historyAbs = path.resolve(String(opts.historyFile));\n const historyRaw = await fs.readFile(historyAbs, 'utf8');\n const entries = JSON.parse(historyRaw) as QueryHistoryEntry[];\n if (!Array.isArray(entries)) {\n throw new Error(\n `--history-file ${historyAbs} did not parse to an array of QueryHistoryEntry.`,\n );\n }\n const report = findMaterializedViewCandidates(entries, {\n thresholdRuns: Number(opts.thresholdRuns ?? '5'),\n thresholdTotalMs: Number(opts.thresholdTotalMs ?? '60000'),\n topN: Number(opts.topN ?? '25'),\n mvSchema: opts.mvSchema ? String(opts.mvSchema) : undefined,\n });\n const output =\n String(opts.format).toLowerCase() === 'json'\n ? JSON.stringify(report, null, 2)\n : renderMvCandidatesMarkdown(report);\n if (opts.out) {\n const out = path.resolve(String(opts.out));\n await fs.mkdir(path.dirname(out), { recursive: true });\n await fs.writeFile(out, output, 'utf8');\n console.error(\n `Wrote ${out} — ${report.candidates.length} MV candidate(s) (scanned ${report.entryCount} entries).`,\n );\n } else {\n process.stdout.write(output + '\\n');\n }\n });\n cmd.addCommand(mvCandidates);\n\n const warehouseSize = new Command('warehouse-size');\n warehouseSize\n .description(\n 'Per-SQL-warehouse sizing recommendation from a query-history snapshot (PERF.5). ' +\n 'Offline — feeds a JSON QueryHistoryEntry[] via --history-file. Suggests size-up / size-down / multi-cluster / keep.',\n )\n .requiredOption(\n '--history-file <path>',\n 'Path to a JSON file containing a QueryHistoryEntry[].',\n )\n .option(\n '--slow-query-ms <n>',\n 'Threshold above which a query counts as \"slow\" (default 30000).',\n '30000',\n )\n .option(\n '--size-up-fraction <p>',\n 'Fraction of slow queries that triggers size-up (default 0.2).',\n '0.2',\n )\n .option(\n '--size-down-mean-ms <n>',\n 'Mean-duration cap below which size-down may trigger (default 1000).',\n '1000',\n )\n .option(\n '--low-use-runs <n>',\n 'Run-count cap below which size-down may trigger (default 20).',\n '20',\n )\n .option(\n '--multi-cluster-runs <n>',\n 'Run-count floor above which size-up upgrades to multi-cluster (default 500).',\n '500',\n )\n .option('--format <fmt>', 'Output format: text | json. Default text.', 'text')\n .option('-o, --out <path>', 'Write report to a file instead of stdout.')\n .action(async (opts) => {\n const historyAbs = path.resolve(String(opts.historyFile));\n const historyRaw = await fs.readFile(historyAbs, 'utf8');\n const entries = JSON.parse(historyRaw) as QueryHistoryEntry[];\n if (!Array.isArray(entries)) {\n throw new Error(\n `--history-file ${historyAbs} did not parse to an array of QueryHistoryEntry.`,\n );\n }\n const report = recommendWarehouseSize(entries, {\n slowQueryThresholdMs: Number(opts.slowQueryMs ?? '30000'),\n sizeUpSlowFraction: Number(opts.sizeUpFraction ?? '0.2'),\n sizeDownMeanMaxMs: Number(opts.sizeDownMeanMs ?? '1000'),\n lowUseRunThreshold: Number(opts.lowUseRuns ?? '20'),\n multiClusterRunThreshold: Number(opts.multiClusterRuns ?? '500'),\n });\n const output =\n String(opts.format).toLowerCase() === 'json'\n ? JSON.stringify(report, null, 2)\n : renderWarehouseSizingMarkdown(report);\n if (opts.out) {\n const out = path.resolve(String(opts.out));\n await fs.mkdir(path.dirname(out), { recursive: true });\n await fs.writeFile(out, output, 'utf8');\n console.error(\n `Wrote ${out} — ${report.recommendations.length} warehouse(s) analysed (scanned ${report.entryCount} entries).`,\n );\n } else {\n process.stdout.write(output + '\\n');\n }\n });\n cmd.addCommand(warehouseSize);\n return cmd;\n}\n","/**\n * XPM.7 — `ddt migrate-platform --to snowflake <path>`\n *\n * Translates Databricks SQL files to Snowflake equivalents using the XPM.4\n * table/view emitter. Accepts a single .sql file or a directory of .sql files.\n * Outputs translated DDL to stdout (default) or --output <dir>.\n *\n * Byte-aligned with `Snowflake/packages/cli/src/commands/migrate-platform.ts`.\n */\nimport path from 'node:path';\nimport fs from 'node:fs/promises';\nimport { Command } from 'commander';\nimport { translateTableDatabricksToSnowflake } from '@ddt-tools/core/migrate';\nimport { logger } from '../util/logger.js';\n\nasync function collectSqlFiles(inputPath: string): Promise<string[]> {\n let stat: Awaited<ReturnType<typeof fs.stat>>;\n try {\n stat = await fs.stat(inputPath);\n } catch {\n return [];\n }\n if (stat.isFile()) {\n return inputPath.endsWith('.sql') ? [inputPath] : [];\n }\n const entries = await fs.readdir(inputPath, { withFileTypes: true });\n const files: string[] = [];\n for (const entry of entries) {\n const full = path.join(inputPath, entry.name);\n if (entry.isDirectory()) {\n files.push(...(await collectSqlFiles(full)));\n } else if (entry.name.endsWith('.sql')) {\n files.push(full);\n }\n }\n return files;\n}\n\nexport function migratePlatformCommand(): Command {\n const cmd = new Command('migrate-platform');\n cmd\n .description(\n 'Translate Databricks SQL files to another platform dialect. ' +\n 'v1: --to snowflake. Reads .sql files from <path> (file or directory).',\n )\n .argument('<path>', 'Source .sql file or directory containing .sql files.')\n .requiredOption('--to <platform>', 'Target platform. Must be \"snowflake\".')\n .option('--output <dir>', 'Write translated files to this directory. Default: stdout.')\n .option(\n '--warn-on-unsupported',\n 'Exit with code 1 if any column type cannot be translated.',\n false,\n )\n .action(\n async (\n inputPath: string,\n opts: { to: string; output?: string; warnOnUnsupported: boolean },\n ) => {\n const target = opts.to.toLowerCase();\n if (target !== 'snowflake') {\n logger.error(\n `ddt migrate-platform --to ${opts.to}: unknown target. Only \"snowflake\" is supported.`,\n );\n process.exitCode = 1;\n return;\n }\n\n const resolved = path.resolve(inputPath);\n // If the path is a .ddtproj file, translate its containing directory.\n const root = resolved.endsWith('.ddtproj') ? path.dirname(resolved) : resolved;\n const sqlFiles = await collectSqlFiles(root);\n\n if (sqlFiles.length === 0) {\n logger.warn(`No .sql files found at ${root}`);\n return;\n }\n\n logger.info(`Translating ${sqlFiles.length} file(s) → Snowflake…`);\n let anyUnsupported = false;\n\n for (const file of sqlFiles) {\n // When the user passes a single .sql file, `root === file` and\n // `path.relative(root, file)` is empty — fall back to the basename\n // so the `-- Source:` header shows the filename, and so the --output\n // destination is `output/<basename>` not the output dir path itself.\n const rel = root === file ? path.basename(file) : path.relative(root, file);\n const ddl = await fs.readFile(file, 'utf8');\n const result = translateTableDatabricksToSnowflake(ddl);\n\n if (result.hasUnsupported) anyUnsupported = true;\n for (const w of result.warnings) {\n logger.warn(`[${rel}] ${w}`);\n }\n\n if (opts.output) {\n const dest = path.join(path.resolve(opts.output), rel);\n await fs.mkdir(path.dirname(dest), { recursive: true });\n await fs.writeFile(dest, result.sql, 'utf8');\n logger.success(`Wrote ${dest}`);\n } else {\n process.stdout.write(`-- Source: ${rel}\\n${result.sql}\\n\\n`);\n }\n }\n\n if (opts.warnOnUnsupported && anyUnsupported) {\n logger.error('One or more column types could not be translated (see warnings above).');\n process.exitCode = 1;\n }\n },\n );\n\n return cmd;\n}\n","/**\n * DBT.4-followup CLI — `ddt migrate from-dbt <project-path>`\n *\n * Reads a dbt project from disk and emits a structured migration report\n * (JSON to stdout or --output file). Composes the three already-shipped\n * substrates (byte-aligned with SDT side):\n * - `parseDbtProjectYaml` (DBT.4-followup parser shipped iter 25)\n * - `parseDbtSourcesYaml` (DBT.4-followup parser shipped iter 25)\n * - `migrateFromDbtManifest` (DBT.4 substrate shipped iter 18 Opus)\n *\n * The CLI does NOT (yet) attempt to write a full `.ddtproj` + per-object\n * `.sql` files — that's a follow-up step. The current surface produces\n * the structured `DbtMigrationResult` shape an operator can pipe into\n * downstream automation or review by hand.\n *\n * NOT in scope:\n * - Writing `.ddtproj` + `.sql` skeleton on disk (separate followup).\n * - DBT.6 macro translation pass on the compiled SQL (caller can run\n * `translateDbtMacros` separately; we surface the unresolved SQL).\n *\n * Byte-aligned with `Snowflake/packages/cli/src/commands/migrate-from-dbt.ts`.\n */\nimport path from 'node:path';\nimport fs from 'node:fs/promises';\nimport { Command } from 'commander';\nimport {\n parseDbtProjectYaml,\n parseDbtSourcesYaml,\n migrateFromDbtManifest,\n type DbtManifestInput,\n type DbtMigrationOptions,\n type DbtMigrationResult,\n type DbtProjectInfo,\n type DbtSourcesInfo,\n type IdentifierCase,\n} from '@ddt-tools/core/migrate';\nimport { logger } from '../util/logger.js';\n\nexport interface MigrateFromDbtReport {\n projectInfo: DbtProjectInfo;\n sourcesInfo?: DbtSourcesInfo;\n migration: DbtMigrationResult;\n inputs: {\n projectPath: string;\n manifestPath: string;\n sourcesPaths: string[];\n };\n}\n\nasync function readJsonFile(filePath: string): Promise<DbtManifestInput> {\n const raw = await fs.readFile(filePath, 'utf-8');\n return JSON.parse(raw) as DbtManifestInput;\n}\n\nasync function readTextFile(filePath: string): Promise<string | undefined> {\n try {\n return await fs.readFile(filePath, 'utf-8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return undefined;\n throw err;\n }\n}\n\n/**\n * Walk a dbt project directory and load the three input files we know\n * about. Returns paths + raw bytes; the orchestration function uses these.\n *\n * Expected layout (dbt defaults):\n * <root>/\n * dbt_project.yml\n * target/\n * manifest.json\n * models/**\\/_sources.yml (or schema.yml)\n *\n * `manifestPath` is overridable so callers can point at a manifest cached\n * elsewhere (CI, pre-compiled artifact).\n */\nasync function discoverDbtFiles(\n rootPath: string,\n manifestPathOverride?: string,\n): Promise<{\n projectYamlText: string;\n projectYamlPath: string;\n manifestText: string;\n manifestPath: string;\n sourcesYamlTexts: { path: string; text: string }[];\n}> {\n const projectYamlPath = path.join(rootPath, 'dbt_project.yml');\n const projectYamlText = await readTextFile(projectYamlPath);\n if (projectYamlText === undefined) {\n throw new Error(`dbt_project.yml not found at ${projectYamlPath}`);\n }\n\n const manifestPath = manifestPathOverride ?? path.join(rootPath, 'target', 'manifest.json');\n const manifestText = await readTextFile(manifestPath);\n if (manifestText === undefined) {\n throw new Error(\n `manifest.json not found at ${manifestPath} — run \"dbt compile\" first or pass --manifest`,\n );\n }\n\n // Look for sources YAMLs anywhere under models/. Best-effort; the\n // migrator works without these (manifest carries sources too).\n const modelsRoot = path.join(rootPath, 'models');\n const sourcesYamlTexts: { path: string; text: string }[] = [];\n try {\n await walkForSourcesYaml(modelsRoot, sourcesYamlTexts);\n } catch {\n // models/ might not exist (esoteric project layouts); skip silently.\n }\n\n return { projectYamlText, projectYamlPath, manifestText, manifestPath, sourcesYamlTexts };\n}\n\nasync function walkForSourcesYaml(\n dirPath: string,\n out: { path: string; text: string }[],\n): Promise<void> {\n const entries = await fs.readdir(dirPath, { withFileTypes: true });\n for (const entry of entries) {\n const full = path.join(dirPath, entry.name);\n if (entry.isDirectory()) {\n await walkForSourcesYaml(full, out);\n continue;\n }\n if (\n entry.name === 'sources.yml' ||\n entry.name === 'sources.yaml' ||\n entry.name === '_sources.yml' ||\n entry.name === '_sources.yaml'\n ) {\n const text = await fs.readFile(full, 'utf-8');\n out.push({ path: full, text });\n }\n }\n}\n\n/**\n * End-to-end migration orchestrator. Pure given the input bytes — the\n * filesystem walk happens upstream so this remains test-friendly.\n */\nexport function buildMigrateFromDbtReport(inputs: {\n projectYamlText: string;\n projectYamlPath: string;\n manifestText: string;\n manifestPath: string;\n sourcesYamlTexts: { path: string; text: string }[];\n options?: {\n identifierCase?: IdentifierCase;\n defaultDatabase?: string;\n defaultSchema?: string;\n };\n}): MigrateFromDbtReport {\n const projectInfo = parseDbtProjectYaml(inputs.projectYamlText);\n\n // Combine all sources.yml files. The DDT-side / SDT-side parsers are\n // file-scoped; we aggregate at the CLI level.\n let sourcesInfo: DbtSourcesInfo | undefined;\n if (inputs.sourcesYamlTexts.length > 0) {\n const combined: DbtSourcesInfo = { sources: [], warnings: [] };\n for (const f of inputs.sourcesYamlTexts) {\n const parsed = parseDbtSourcesYaml(f.text);\n combined.sources.push(...parsed.sources);\n combined.warnings.push(...parsed.warnings.map((w) => `${f.path}: ${w}`));\n }\n sourcesInfo = combined;\n }\n\n const manifest: DbtManifestInput = JSON.parse(inputs.manifestText) as DbtManifestInput;\n\n // Caller-overrides win; otherwise infer reasonable defaults from\n // project.yml's first per-path entry that has database/schema set.\n const inferredDefault = projectInfo.perPath.find((p) => p.database || p.schema);\n const migOpts: DbtMigrationOptions = {\n identifierCase: inputs.options?.identifierCase ?? 'preserve',\n ...((inputs.options?.defaultDatabase ?? inferredDefault?.database)\n ? { defaultDatabase: inputs.options?.defaultDatabase ?? inferredDefault?.database }\n : {}),\n ...((inputs.options?.defaultSchema ?? inferredDefault?.schema)\n ? { defaultSchema: inputs.options?.defaultSchema ?? inferredDefault?.schema }\n : {}),\n };\n\n const migration = migrateFromDbtManifest(manifest, migOpts);\n\n return {\n projectInfo,\n ...(sourcesInfo ? { sourcesInfo } : {}),\n migration,\n inputs: {\n projectPath: inputs.projectYamlPath,\n manifestPath: inputs.manifestPath,\n sourcesPaths: inputs.sourcesYamlTexts.map((f) => f.path),\n },\n };\n}\n\nexport function migrateFromDbtCommand(): Command {\n const cmd = new Command('migrate');\n cmd.description('Migrate from another tool to SDT (`from-dbt` subcommand only in v1).');\n\n cmd\n .command('from-dbt')\n .description(\n 'Read a dbt project (dbt_project.yml + target/manifest.json + sources.yml files) ' +\n 'and emit a structured migration report (`DbtMigrationResult`) to stdout or --output.',\n )\n .argument(\n '<project-path>',\n 'Path to the dbt project root (the directory containing dbt_project.yml).',\n )\n .option(\n '--manifest <path>',\n 'Override the manifest path. Default: <project-path>/target/manifest.json.',\n )\n .option('--output <path>', 'Write JSON report to this file. Default: stdout.')\n .option('--identifier-case <case>', 'preserve | upper | lower. Default: preserve.', 'preserve')\n .option(\n '--default-database <name>',\n \"Fallback database when the manifest entry doesn't pin one.\",\n )\n .option('--default-schema <name>', \"Fallback schema when the manifest entry doesn't pin one.\")\n .action(\n async (\n projectPath: string,\n options: {\n manifest?: string;\n output?: string;\n identifierCase?: string;\n defaultDatabase?: string;\n defaultSchema?: string;\n },\n ) => {\n const resolved = path.resolve(projectPath);\n let discovered;\n try {\n discovered = await discoverDbtFiles(resolved, options.manifest);\n } catch (err) {\n logger.error(`migrate from-dbt: ${(err as Error).message}`);\n process.exitCode = 1;\n return;\n }\n const idCase = (options.identifierCase ?? 'preserve') as IdentifierCase;\n if (!['preserve', 'upper', 'lower'].includes(idCase)) {\n logger.error(\n `--identifier-case must be one of preserve | upper | lower (got \"${idCase}\")`,\n );\n process.exitCode = 1;\n return;\n }\n const report = buildMigrateFromDbtReport({\n projectYamlText: discovered.projectYamlText,\n projectYamlPath: discovered.projectYamlPath,\n manifestText: discovered.manifestText,\n manifestPath: discovered.manifestPath,\n sourcesYamlTexts: discovered.sourcesYamlTexts,\n options: {\n identifierCase: idCase,\n ...(options.defaultDatabase ? { defaultDatabase: options.defaultDatabase } : {}),\n ...(options.defaultSchema ? { defaultSchema: options.defaultSchema } : {}),\n },\n });\n const json = JSON.stringify(report, null, 2);\n if (options.output) {\n await fs.writeFile(options.output, json);\n logger.info(\n `migrate from-dbt: wrote report to ${options.output} — ${report.migration.models.length} models / ${report.migration.sources.length} sources / ${report.migration.diagnostics.length} diagnostics`,\n );\n } else {\n process.stdout.write(json + '\\n');\n }\n },\n );\n\n return cmd;\n}\n\n// Re-export the orchestrator for direct programmatic / test usage. Note:\n// `readJsonFile` is intentionally not exported (filesystem-coupling stays\n// behind the CLI surface).\nexport { readJsonFile as _readJsonFile_internalForTests };\n","/**\n * `ddt backlog score` — pure local-compute backlog scorer (LOCAL.1).\n *\n * Walks the project's `docs/BACKLOG.md` (or `--source <path>`), applies\n * the deterministic `/next` scoring formula, and emits a stable JSON\n * array of `{id, title, family, cluster, status, tier, model, score,\n * complexity, risk, paired, closesCluster, dependsOn, area}`. The\n * `/next` propose phase reads this instead of re-deriving scores\n * in-band — saves ~5k tokens per call.\n *\n * Flags:\n * --source <path> Override the default BACKLOG.md location.\n * --format json|markdown Output format (default json).\n * --explain-scores Append per-item formula breakdown (markdown).\n * --no-cluster-bias Skip the cluster-closing bias subtraction.\n *\n * Mirrors `Snowflake/packages/cli/src/commands/backlog.ts`.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { backlogScore } from '@ddt-tools/core';\n\nconst DEFAULT_BACKLOG_CANDIDATES = [\n path.join('docs', 'BACKLOG.md'),\n path.join('..', 'docs', 'BACKLOG.md'),\n path.join('..', '..', 'docs', 'BACKLOG.md'),\n path.join('..', '..', '..', 'docs', 'BACKLOG.md'),\n];\n\nexport function backlogCommand(): Command {\n const cmd = new Command('backlog');\n cmd.description('Local-compute backlog tooling. Pure parse + score; no warehouse contact.');\n\n cmd\n .command('score')\n .description(\n 'Score docs/BACKLOG.md per the /next formula. Default: JSON to stdout. Use --explain-scores for a human-readable breakdown.',\n )\n .option('--source <path>', 'Override the BACKLOG.md path.')\n .option('--format <fmt>', 'json | markdown (default json).', 'json')\n .option('--explain-scores', 'Append per-item formula breakdown.', false)\n .option('--no-cluster-bias', 'Skip the cluster-closing bias subtraction.')\n .action(async (opts) => {\n const sourcePath = await resolveBacklogPath(opts.source);\n const markdown = await fs.readFile(sourcePath, 'utf8');\n const applyClusterClosingBias = opts.clusterBias !== false;\n const scored = backlogScore.scoreBacklog(markdown, { applyClusterClosingBias });\n\n const fmt = String(opts.format ?? 'json').toLowerCase();\n if (fmt === 'json') {\n process.stdout.write(JSON.stringify(scored, null, 2) + '\\n');\n if (opts.explainScores) {\n for (const item of scored) {\n process.stderr.write('\\n' + backlogScore.formatScoreExplanation(item) + '\\n');\n }\n }\n return;\n }\n if (fmt === 'markdown') {\n emitMarkdown(scored, Boolean(opts.explainScores));\n return;\n }\n throw new Error(`Unknown --format: ${opts.format}. Use json | markdown.`);\n });\n\n return cmd;\n}\n\nasync function resolveBacklogPath(override: string | undefined): Promise<string> {\n if (override) {\n return path.resolve(override);\n }\n for (const rel of DEFAULT_BACKLOG_CANDIDATES) {\n const candidate = path.resolve(rel);\n try {\n await fs.access(candidate);\n return candidate;\n } catch {\n // Not at this depth — try the next.\n }\n }\n throw new Error(\n 'BACKLOG.md not found in CWD or any parent up to depth 3. Pass --source <path> to override.',\n );\n}\n\nfunction emitMarkdown(scored: readonly backlogScore.ScoredBacklogItem[], explain: boolean): void {\n process.stdout.write('| id | cluster | complexity | risk | paired | closes | score |\\n');\n process.stdout.write('|---|---|---|---|---|---|---|\\n');\n for (const item of scored) {\n process.stdout.write(\n `| ${item.id} | ${item.cluster} | ${item.complexity ?? '?'} | ${item.risk} | ${item.paired ? 'Y' : ''} | ${item.closesCluster ? '★' : ''} | ${item.score ?? '?'} |\\n`,\n );\n }\n if (explain) {\n for (const item of scored) {\n process.stdout.write('\\n' + backlogScore.formatScoreExplanation(item) + '\\n');\n }\n }\n}\n","/**\n * `ddt watch` — platform-feature drift bulletin (WATCH.2-paired).\n *\n * Wires the shipped `@ddt-tools/core/platformWatch` substrate trio (WATCH.1\n * parse+diff+persist, WATCH.5 coverage, WATCH.4 bulletin) into a host-\n * level CLI: read prior snapshot JSON + current release-notes markdown\n * from disk, run `buildMonthlyBulletin`, emit JSON or rendered Markdown.\n * Optional `--save-snapshot` writes the parsed current set to disk so\n * the next run has a fresh prior.\n *\n * Pure file I/O — the substrate stays I/O-free; the CLI owns the disk\n * boundary per the substrate's design contract.\n *\n * Mirrors `Snowflake/packages/cli/src/commands/watch.ts`.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { platformWatch } from '@ddt-tools/core';\n\nconst DEFAULT_SOURCE = 'databricks';\n\nexport function watchCommand(): Command {\n const cmd = new Command('watch');\n cmd.description(\n 'Platform-feature drift detector. Diffs release-notes markdown against a cached snapshot.',\n );\n\n cmd\n .command('bulletin')\n .description(\n 'Compose a monthly bulletin: new drift (needs BACKLOG action), new covered, removed. Reads --prior snapshot JSON + --current release-notes markdown.',\n )\n .requiredOption('--current <path>', 'Path to current release-notes markdown.')\n .option('--prior <path>', 'Path to prior snapshot JSON (defaults to empty prior).')\n .option('--rules <path>', 'Path to cluster-match rules JSON (ClusterMatchRule[]).')\n .option('--overrides <path>', 'Path to release-note-id → cluster override JSON.')\n .option('--source <label>', 'Source label written into a saved snapshot.', DEFAULT_SOURCE)\n .option('--format <fmt>', 'json | markdown (default markdown).', 'markdown')\n .option('--save-snapshot <path>', 'Also write the parsed current set as a fresh snapshot.')\n .action(async (opts) => {\n const currentMarkdown = await fs.readFile(path.resolve(opts.current), 'utf8');\n const currentNotes = platformWatch.parseReleaseNotesMarkdown(currentMarkdown);\n\n const priorNotes = opts.prior ? await readPriorSnapshot(path.resolve(opts.prior)) : [];\n const rules = opts.rules ? await readClusterRules(path.resolve(opts.rules)) : [];\n const overrides = opts.overrides\n ? await readOverrides(path.resolve(opts.overrides))\n : undefined;\n\n const bulletin = platformWatch.buildMonthlyBulletin({\n prior: priorNotes,\n current: currentNotes,\n rules,\n overrides,\n });\n\n const fmt = String(opts.format ?? 'markdown').toLowerCase();\n if (fmt === 'json') {\n process.stdout.write(JSON.stringify(bulletin, null, 2) + '\\n');\n } else if (fmt === 'markdown') {\n process.stdout.write(platformWatch.renderBulletinMarkdown(bulletin) + '\\n');\n } else {\n throw new Error(`Unknown --format: ${opts.format}. Use json | markdown.`);\n }\n\n if (opts.saveSnapshot) {\n const snapshot = platformWatch.serializeReleaseNotesSnapshot(\n String(opts.source ?? DEFAULT_SOURCE),\n currentNotes,\n );\n await fs.writeFile(\n path.resolve(opts.saveSnapshot),\n JSON.stringify(snapshot, null, 2) + '\\n',\n 'utf8',\n );\n }\n });\n\n return cmd;\n}\n\nasync function readPriorSnapshot(filePath: string): Promise<readonly platformWatch.ReleaseNote[]> {\n const raw = await fs.readFile(filePath, 'utf8');\n const parsed: unknown = JSON.parse(raw);\n const snapshot = platformWatch.deserializeReleaseNotesSnapshot(parsed);\n if (snapshot === null) {\n throw new Error(\n `Prior snapshot at ${filePath} is malformed or carries an unsupported version. Pass a fresh --prior or omit the flag.`,\n );\n }\n return snapshot.notes;\n}\n\nasync function readClusterRules(\n filePath: string,\n): Promise<readonly platformWatch.ClusterMatchRule[]> {\n const raw = await fs.readFile(filePath, 'utf8');\n const parsed: unknown = JSON.parse(raw);\n if (!Array.isArray(parsed)) {\n throw new Error(`--rules at ${filePath} must be a JSON array of ClusterMatchRule.`);\n }\n return parsed as platformWatch.ClusterMatchRule[];\n}\n\nasync function readOverrides(filePath: string): Promise<platformWatch.ReleaseNoteOverride> {\n const raw = await fs.readFile(filePath, 'utf8');\n const parsed: unknown = JSON.parse(raw);\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error(`--overrides at ${filePath} must be a JSON object of {id: cluster}.`);\n }\n return parsed as platformWatch.ReleaseNoteOverride;\n}\n","/**\n * `ddt bookmarks` — operator-facing CRUD over saved bookmarks (AUTH.6).\n *\n * Persists to `~/.ddt/bookmarks.json` (override with `--store <path>`).\n * Composes with the pure `@ddt-tools/core/bookmarks` substrate — this file\n * is the disk-I/O boundary; the substrate stays pure.\n *\n * Subcommands:\n * ddt bookmarks add <name> --type query|file|section --target <s> [--label <s>]\n * ddt bookmarks remove <name>\n * ddt bookmarks list [--format text|json]\n * ddt bookmarks get <name> [--format text|json]\n *\n * Mirrors `Snowflake/packages/cli/src/commands/bookmarks.ts`.\n */\nimport { promises as fs } from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { bookmarks } from '@ddt-tools/core';\n\nconst DEFAULT_STORE = path.join(os.homedir(), '.ddt', 'bookmarks.json');\n\nexport function bookmarksCommand(): Command {\n const cmd = new Command('bookmarks');\n cmd.description('Save fast-access pointers to queries, files, or named sections.');\n cmd.option('--store <path>', 'Override the bookmarks JSON path.', DEFAULT_STORE);\n\n cmd\n .command('add <name>')\n .description('Add a bookmark.')\n .requiredOption('--type <type>', 'Target type: query | file | section.')\n .requiredOption('--target <target>', 'Target payload (SQL text, file path, or section URI).')\n .option('--label <label>', 'Display label (defaults to name).')\n .action(async (name: string, opts) => {\n const storePath = resolveStorePath(cmd.opts().store);\n const store = await loadStore(storePath);\n const created = store.add({\n name,\n type: opts.type as bookmarks.BookmarkType,\n target: opts.target,\n label: opts.label,\n });\n await saveStore(storePath, store);\n process.stdout.write(`Added bookmark '${created.name}' (${created.type}).\\n`);\n });\n\n cmd\n .command('remove <name>')\n .description('Remove a bookmark by name (case-insensitive).')\n .action(async (name: string) => {\n const storePath = resolveStorePath(cmd.opts().store);\n const store = await loadStore(storePath);\n const removed = store.remove(name);\n if (!removed) {\n throw new Error(`No bookmark named '${name}'.`);\n }\n await saveStore(storePath, store);\n process.stdout.write(`Removed bookmark '${name}'.\\n`);\n });\n\n cmd\n .command('list')\n .description('List every bookmark.')\n .option('--format <fmt>', 'text | json (default text).', 'text')\n .action(async (opts) => {\n const storePath = resolveStorePath(cmd.opts().store);\n const store = await loadStore(storePath);\n const list = store.list();\n const fmt = String(opts.format ?? 'text').toLowerCase();\n if (fmt === 'json') {\n process.stdout.write(JSON.stringify(list, null, 2) + '\\n');\n return;\n }\n if (fmt !== 'text') {\n throw new Error(`Unknown --format: ${opts.format}. Use text | json.`);\n }\n if (list.length === 0) {\n process.stdout.write(\n 'No bookmarks. Add one with `ddt bookmarks add <name> --type ... --target ...`.\\n',\n );\n return;\n }\n for (const b of list) {\n const label = b.label ?? b.name;\n process.stdout.write(\n `${b.name} [${b.type}] → ${b.target}${label !== b.name ? ` (${label})` : ''}\\n`,\n );\n }\n });\n\n cmd\n .command('get <name>')\n .description('Look up a single bookmark by name.')\n .option('--format <fmt>', 'text | json (default json).', 'json')\n .action(async (name: string, opts) => {\n const storePath = resolveStorePath(cmd.opts().store);\n const store = await loadStore(storePath);\n const found = store.findByName(name);\n if (found === undefined) {\n throw new Error(`No bookmark named '${name}'.`);\n }\n const fmt = String(opts.format ?? 'json').toLowerCase();\n if (fmt === 'json') {\n process.stdout.write(JSON.stringify(found, null, 2) + '\\n');\n return;\n }\n if (fmt !== 'text') {\n throw new Error(`Unknown --format: ${opts.format}. Use text | json.`);\n }\n process.stdout.write(`${found.name} [${found.type}] → ${found.target}\\n`);\n });\n\n return cmd;\n}\n\nfunction resolveStorePath(override: string | undefined): string {\n return path.resolve(override ?? DEFAULT_STORE);\n}\n\nasync function loadStore(storePath: string): Promise<bookmarks.BookmarkStore> {\n try {\n const raw = await fs.readFile(storePath, 'utf8');\n const parsed: unknown = JSON.parse(raw);\n return bookmarks.BookmarkStore.deserialize(parsed);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n return new bookmarks.BookmarkStore();\n }\n throw err;\n }\n}\n\nasync function saveStore(storePath: string, store: bookmarks.BookmarkStore): Promise<void> {\n const dir = path.dirname(storePath);\n await fs.mkdir(dir, { recursive: true });\n await fs.writeFile(storePath, JSON.stringify(store.serialize(), null, 2) + '\\n', 'utf8');\n}\n","/**\n * `ddt snippets` — list + show the shipped snippets catalog (AUTH.2).\n *\n * Composes the pure `@ddt-tools/core/snippets` catalog into operator-facing\n * surfaces. List mode pages through every snippet (filterable by\n * category); show mode prints a single snippet's rendered body suitable\n * for copy-paste into a `.sql` file.\n *\n * Subcommands:\n * ddt snippets list [--category <c>] [--format text|json]\n * ddt snippets show <id> [--format text|json|raw]\n *\n * Mirrors `Snowflake/packages/cli/src/commands/snippets.ts`.\n */\nimport { Command } from 'commander';\nimport { snippets } from '@ddt-tools/core';\n\nexport function snippetsCommand(): Command {\n const cmd = new Command('snippets');\n cmd.description('Browse the built-in SQL snippet catalog (SCD, star schema, data quality).');\n\n cmd\n .command('list')\n .description('List every snippet (filterable by category).')\n .option(\n '--category <cat>',\n 'Filter by category: scd | star-schema | snowflake-schema | standards | data-quality.',\n )\n .option('--format <fmt>', 'text | json (default text).', 'text')\n .action((opts) => {\n const list = opts.category\n ? snippets.listSnippets(opts.category as snippets.SnippetCategory)\n : snippets.listSnippets();\n const fmt = String(opts.format ?? 'text').toLowerCase();\n if (fmt === 'json') {\n process.stdout.write(\n JSON.stringify(\n list.map((s) => ({\n id: s.id,\n name: s.name,\n category: s.category,\n description: s.description,\n })),\n null,\n 2,\n ) + '\\n',\n );\n return;\n }\n if (fmt !== 'text') {\n throw new Error(`Unknown --format: ${opts.format}. Use text | json.`);\n }\n if (list.length === 0) {\n process.stdout.write('No snippets matched. Try `ddt snippets list` without --category.\\n');\n return;\n }\n for (const s of list) {\n process.stdout.write(`${s.id} [${s.category}] — ${s.name}\\n ${s.description}\\n`);\n }\n });\n\n cmd\n .command('show <id>')\n .description('Print a single snippet by id.')\n .option(\n '--format <fmt>',\n 'text (rendered, placeholders inline) | raw (VS Code syntax) | json (default text).',\n 'text',\n )\n .action((id: string, opts) => {\n const found = snippets.findSnippet(id);\n if (found === undefined) {\n throw new Error(`No snippet named '${id}'. Run \\`ddt snippets list\\` to see options.`);\n }\n const fmt = String(opts.format ?? 'text').toLowerCase();\n if (fmt === 'json') {\n process.stdout.write(JSON.stringify(found, null, 2) + '\\n');\n return;\n }\n if (fmt === 'raw') {\n process.stdout.write(found.body + '\\n');\n return;\n }\n if (fmt !== 'text') {\n throw new Error(`Unknown --format: ${opts.format}. Use text | json | raw.`);\n }\n process.stdout.write(`-- ${found.name}\\n-- ${found.description}\\n`);\n process.stdout.write(snippets.renderSnippetBody(found) + '\\n');\n });\n\n return cmd;\n}\n","/**\n * `ddt generate` — code generation CLI (GENPY.5).\n *\n * Three subcommands wiring GENPY.2-4 substrates onto the operator surface:\n *\n * ddt generate notebook --from-json <path> --target <fqn> --source <path>\n * [--runtime <ver>] [--merge-schema] [--write-mode append|overwrite]\n * [--out <dir>]\n *\n * ddt generate scd --table <fqn> --natural-key <cols> [--type 1|2]\n * [--effective-from <col>] [--effective-to <col>]\n * [--is-current <col>] [--hash-cols <cols>]\n * [--surrogate-key <col>] [--out <dir>]\n *\n * ddt generate star-pipeline --from-design <path>\n * [--format pyspark|sparksql|snowpark]\n * [--schema <catalog.schema>] [--out <dir>]\n *\n * Mirrors `Snowflake/packages/cli/src/commands/generate.ts`.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { generate } from '@ddt-tools/core';\nimport type { SCDStrategy } from '@ddt-tools/core';\n\n// ── notebook ──────────────────────────────────────────────────────────────────\n\nfunction notebookSubcommand(): Command {\n return new Command('notebook')\n .description('Emit a Databricks PySpark ingest notebook from a JSON sample file.')\n .requiredOption('--from-json <path>', 'Path to a JSON data file (array of records or NDJSON).')\n .requiredOption('--target <fqn>', 'Target table FQN (catalog.schema.table).')\n .requiredOption('--source <path>', 'Source path for the read (S3 / DBFS / volume path).')\n .option('--runtime <ver>', 'Databricks Runtime version tag (e.g. dbr15.4-lts).', 'dbr14.3-lts')\n .option('--merge-schema', 'Emit mergeSchema option for schema evolution.', false)\n .option('--write-mode <mode>', 'append | overwrite (default append).', 'append')\n .option('--out <dir>', 'Write .ipynb + .py to this directory instead of stdout.')\n .action(async (opts) => {\n const rows = await readJsonRows(opts.fromJson);\n const schema = await generate.inferTypes(rows);\n const result = generate.emitIngestNotebook(schema, {\n targetFqn: opts.target,\n sourcePath: opts.source,\n runtime: opts.runtime,\n mergeSchema: Boolean(opts.mergeSchema),\n writeMode: opts.writeMode === 'overwrite' ? 'overwrite' : 'append',\n });\n\n if (opts.out) {\n await fs.mkdir(path.resolve(opts.out), { recursive: true });\n const stem = sanitizeFileStem(opts.target);\n await fs.writeFile(\n path.join(path.resolve(opts.out), `ingest_${stem}.ipynb`),\n JSON.stringify(result.ipynb, null, 2) + '\\n',\n 'utf8',\n );\n await fs.writeFile(\n path.join(path.resolve(opts.out), `ingest_${stem}.py`),\n result.py,\n 'utf8',\n );\n } else {\n process.stdout.write(result.py);\n }\n });\n}\n\n// ── scd ───────────────────────────────────────────────────────────────────────\n\nfunction scdSubcommand(): Command {\n return new Command('scd')\n .description('Emit SCD PySpark + SparkSQL merge code for a given table and strategy.')\n .requiredOption('--table <fqn>', 'Target table FQN (catalog.schema.table).')\n .requiredOption('--natural-key <cols>', 'Comma-separated natural key columns.')\n .option('--type <n>', 'SCD type (1 | 2, default 2).', '2')\n .option('--effective-from <col>', 'Effective-from timestamp column.', 'effective_from')\n .option('--effective-to <col>', 'Effective-to timestamp column.', 'effective_to')\n .option('--is-current <col>', 'Is-current boolean column (optional).')\n .option('--hash-cols <cols>', 'Comma-separated columns for hash-based change detection.')\n .option('--surrogate-key <col>', 'Surrogate key column (SCD-2 only).', 'id')\n .option(\n '--on-schema-change <action>',\n 'add-column | fail | rebuild (default add-column).',\n 'add-column',\n )\n .option('--out <dir>', 'Write .py + .sql files to this directory instead of stdout.')\n .action(async (opts) => {\n const naturalKey = String(opts.naturalKey)\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean);\n if (naturalKey.length === 0) {\n throw new Error('--natural-key must list at least one column name.');\n }\n\n const scdType = parseInt(opts.type, 10);\n if (scdType !== 1 && scdType !== 2) {\n throw new Error(`--type must be 1 or 2 (got '${opts.type}').`);\n }\n\n const hashCols = opts.hashCols\n ? String(opts.hashCols)\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean)\n : undefined;\n\n const strategy: SCDStrategy = {\n type: scdType as 1 | 2,\n naturalKey,\n surrogateKeyColumn: scdType === 2 ? opts.surrogateKey : undefined,\n effectiveFromColumn: opts.effectiveFrom,\n effectiveToColumn: opts.effectiveTo,\n isCurrentColumn: opts.isCurrent,\n hashColumns: hashCols,\n onSchemaChange: opts.onSchemaChange as 'add-column' | 'fail' | 'rebuild',\n };\n\n const result = generate.emitScdPyspark(strategy, {\n targetFqn: opts.table,\n sourceFqn: `staging.stg_${sanitizeFileStem(opts.table)}`,\n projectionColumns: naturalKey,\n });\n\n if (opts.out) {\n const stem = sanitizeFileStem(opts.table);\n await fs.mkdir(path.resolve(opts.out), { recursive: true });\n await fs.writeFile(\n path.join(path.resolve(opts.out), `scd_${stem}.py`),\n result.pyspark,\n 'utf8',\n );\n await fs.writeFile(\n path.join(path.resolve(opts.out), `scd_${stem}.sql`),\n result.sparksql,\n 'utf8',\n );\n } else {\n process.stdout.write('-- PySpark --\\n');\n process.stdout.write(result.pyspark + '\\n');\n process.stdout.write('-- SparkSQL --\\n');\n process.stdout.write(result.sparksql + '\\n');\n }\n });\n}\n\n// ── star-pipeline ─────────────────────────────────────────────────────────────\n\nfunction starPipelineSubcommand(): Command {\n return new Command('star-pipeline')\n .description('Emit SCD-2 dim + FK-enrichment fact scaffolds from a designStar result.')\n .requiredOption('--from-design <path>', 'Path to a DesignStarResult JSON file.')\n .option('--format <fmt>', 'pyspark | sparksql | snowpark (default pyspark).', 'pyspark')\n .option('--schema <catalog.schema>', 'Target catalog.schema prefix (default main).')\n .option('--out <dir>', 'Write pipeline files to this directory instead of stdout.')\n .action(async (opts) => {\n const raw = await fs.readFile(path.resolve(opts.fromDesign), 'utf8');\n const parsed: unknown = JSON.parse(raw);\n if (\n parsed === null ||\n typeof parsed !== 'object' ||\n Array.isArray(parsed) ||\n !('factName' in parsed) ||\n !Array.isArray((parsed as Record<string, unknown>).dimensions)\n ) {\n throw new Error(\n `--from-design must point to a DesignStarResult JSON (fields: factName, dimensions, ...).`,\n );\n }\n const design = {\n measureColumns: [],\n assumptions: [],\n proposedInvocation: '',\n needsReview: true as const,\n rawModelText: '',\n parseFailed: false,\n ...(parsed as Record<string, unknown>),\n } as unknown as Parameters<typeof generate.emitStarPipeline>[0];\n\n const fmt = (opts.format ?? 'pyspark') as generate.StarPipelineFormat;\n const validFormats: generate.StarPipelineFormat[] = ['pyspark', 'sparksql', 'snowpark'];\n if (!validFormats.includes(fmt)) {\n throw new Error(`--format must be pyspark | sparksql | snowpark (got '${opts.format}').`);\n }\n\n const result = generate.emitStarPipeline(design, {\n format: fmt,\n targetSchema: opts.schema,\n });\n\n if (opts.out) {\n const outDir = path.resolve(opts.out);\n for (const [relPath, content] of result.files) {\n const dest = path.join(outDir, relPath);\n await fs.mkdir(path.dirname(dest), { recursive: true });\n await fs.writeFile(dest, content, 'utf8');\n }\n } else {\n for (const [relPath, content] of result.files) {\n process.stdout.write(`-- ${relPath} --\\n`);\n process.stdout.write(content + '\\n\\n');\n }\n }\n });\n}\n\n// ── public factory ────────────────────────────────────────────────────────────\n\nexport function generateCommand(): Command {\n const cmd = new Command('generate');\n cmd.description('Code generation: ingest notebooks, SCD merge scripts, star-schema pipelines.');\n cmd.addCommand(notebookSubcommand());\n cmd.addCommand(scdSubcommand());\n cmd.addCommand(starPipelineSubcommand());\n return cmd;\n}\n\n// ── helpers ───────────────────────────────────────────────────────────────────\n\nasync function readJsonRows(filePath: string): Promise<Record<string, unknown>[]> {\n const raw = await fs.readFile(path.resolve(filePath), 'utf8');\n const trimmed = raw.trim();\n if (trimmed.startsWith('[')) {\n const parsed: unknown = JSON.parse(raw);\n if (!Array.isArray(parsed)) throw new Error(`${filePath} must be a JSON array of objects.`);\n return parsed as Record<string, unknown>[];\n }\n // NDJSON\n return trimmed\n .split('\\n')\n .filter((l) => l.trim().length > 0)\n .map((l, i) => {\n const obj: unknown = JSON.parse(l);\n if (obj === null || typeof obj !== 'object' || Array.isArray(obj))\n throw new Error(`Line ${i + 1} of ${filePath} is not a JSON object.`);\n return obj as Record<string, unknown>;\n });\n}\n\n/** `main.marketing.fact_sales` → `main_marketing_fact_sales` */\nfunction sanitizeFileStem(fqn: string): string {\n return fqn\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '_')\n .replace(/^_|_$/g, '');\n}\n","/**\n * `ddt exec <file.sql> --profiles <list>` — AUTH.3.\n *\n * Runs a SQL / DeltaSQL script on one or more connection profiles in\n * parallel and prints a merged report. Guarded against any profile\n * whose name matches \"prod\" or \"production\" (case-insensitive) unless\n * `--yes` is passed.\n *\n * Mirrors `Snowflake/packages/cli/src/commands/exec.ts`.\n */\nimport { Command } from 'commander';\nimport { promises as fs } from 'node:fs';\nimport { getProfile, createConnection } from '@ddt-tools/core/connection';\nimport { queryExecution } from '@ddt-tools/core';\n\nexport interface ExecResult {\n profile: string;\n status: 'success' | 'error';\n rowsAffected?: number;\n durationMs: number;\n error?: string;\n}\n\nexport type ExecFn = (\n profile: string,\n sql: string,\n timeoutMs: number,\n) => Promise<Omit<ExecResult, 'profile' | 'durationMs'>>;\n\nconst PROD_PATTERN = /\\bprod(uction)?\\b/i;\n\nfunction isProductionProfile(name: string): boolean {\n return PROD_PATTERN.test(name);\n}\n\nasync function runOnProfile(\n execFn: ExecFn,\n profile: string,\n sql: string,\n timeoutMs: number,\n): Promise<ExecResult> {\n const start = Date.now();\n try {\n const res = await execFn(profile, sql, timeoutMs);\n return { ...res, profile, durationMs: Date.now() - start };\n } catch (err) {\n return {\n profile,\n status: 'error',\n durationMs: Date.now() - start,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\nfunction renderText(results: ExecResult[]): string {\n const lines: string[] = [];\n for (const r of results) {\n if (r.status === 'success') {\n const rows = r.rowsAffected !== undefined ? ` (${r.rowsAffected} rows)` : '';\n lines.push(` ${r.profile}: ✓${rows} — ${(r.durationMs / 1000).toFixed(1)}s`);\n } else {\n lines.push(` ${r.profile}: ✗ ${r.error ?? 'unknown error'}`);\n }\n }\n const total = results.length;\n const succeeded = results.filter((r) => r.status === 'success').length;\n lines.push(`\\n${succeeded}/${total} profiles succeeded.`);\n return lines.join('\\n');\n}\n\n/**\n * Wire to the real Databricks connection layer:\n * 1. Resolve the named profile (`~/.ddt/profiles.json`).\n * 2. Open a connection (PAT bearer or OAuth, per profile.auth).\n * 3. Split the SQL via the shared `queryExecution.splitStatements`\n * (Databricks dialect: backtick identifiers, no dollar-quotes)\n * and run each statement sequentially through\n * `DatabricksConnection.query`. We do NOT `failFast` so a script\n * with N statements surfaces every error.\n * 4. Aggregate: success iff every statement succeeded; the first\n * error's message becomes the profile-level error. Total\n * `rowsAffected` is the sum of rowCount across statements.\n *\n * Injectable for tests via the `execFn` parameter on `execCommand`.\n */\nasync function defaultExecFn(\n profile: string,\n sql: string,\n timeoutMs: number,\n): Promise<Omit<ExecResult, 'profile' | 'durationMs'>> {\n const profileObj = await getProfile(profile);\n const conn = createConnection(profileObj);\n await conn.connect();\n try {\n const timeoutSeconds = Math.max(1, Math.ceil(timeoutMs / 1000));\n const runner: queryExecution.QueryRunner = {\n executeStatement: async (statement: string) => {\n const result = await conn.query(statement, { timeoutSeconds });\n return {\n rows: result.rows as Record<string, unknown>[],\n durationMs: result.durationMs,\n };\n },\n };\n const result = await queryExecution.executeStatements(sql, runner, {\n failFast: false,\n splitOptions: { dialect: 'databricks' },\n toolName: 'ddt',\n });\n const firstError = result.statements.find((s) => s.error);\n if (firstError && firstError.error) {\n throw new Error(firstError.error.message);\n }\n const rowsAffected = result.statements.reduce((acc, s) => acc + (s.rowCount ?? 0), 0);\n return { status: 'success', rowsAffected };\n } finally {\n await conn.disconnect().catch(() => {\n /* best-effort cleanup */\n });\n }\n}\n\nexport function execCommand(execFn: ExecFn = defaultExecFn): Command {\n const cmd = new Command('exec');\n cmd\n .description('Run a SQL script on one or more connection profiles in parallel.')\n .argument('<file>', 'Path to the .sql file to execute.')\n .requiredOption('--profiles <list>', 'Comma-separated connection profile names.')\n .option('--yes', 'Confirm execution against production profiles without prompting.')\n .option('--format <fmt>', 'text | json (default text).', 'text')\n .option('--timeout <ms>', 'Per-profile timeout in milliseconds.', '30000')\n .action(async (file: string, opts) => {\n const profiles = (opts.profiles as string)\n .split(',')\n .map((p) => p.trim())\n .filter(Boolean);\n if (profiles.length === 0) throw new Error('--profiles must list at least one profile.');\n\n const prodProfiles = profiles.filter(isProductionProfile);\n if (prodProfiles.length > 0 && !opts.yes) {\n throw new Error(\n `Profile(s) look like production: ${prodProfiles.join(', ')}. ` +\n `Pass --yes to confirm.`,\n );\n }\n\n let sql: string;\n try {\n sql = await fs.readFile(file, 'utf8');\n } catch {\n throw new Error(`Cannot read file: ${file}`);\n }\n if (!sql.trim()) throw new Error(`File is empty: ${file}`);\n\n const timeoutMs = parseInt(String(opts.timeout ?? '30000'), 10);\n const results = await Promise.all(\n profiles.map((p) => runOnProfile(execFn, p, sql, timeoutMs)),\n );\n\n const fmt = String(opts.format ?? 'text').toLowerCase();\n if (fmt === 'json') {\n const failed = results.filter((r) => r.status === 'error').length;\n process.stdout.write(\n JSON.stringify(\n {\n results,\n summary: {\n total: results.length,\n succeeded: results.length - failed,\n failed,\n },\n },\n null,\n 2,\n ) + '\\n',\n );\n return;\n }\n if (fmt !== 'text') throw new Error(`Unknown --format: ${opts.format}. Use text | json.`);\n process.stdout.write(renderText(results) + '\\n');\n });\n return cmd;\n}\n","/**\n * `ddt search <pattern> --profiles <list|all>` — AUTH.4.\n *\n * Finds objects whose name matches a pattern across one or more connection\n * profiles. Surfaces presence/absence drift: if an object exists in some\n * profiles but not others, those profiles are flagged.\n *\n * The search is case-insensitive substring match by default; --exact\n * switches to exact name match; --type filters by objectType.\n *\n * Mirrors `Snowflake/packages/cli/src/commands/search.ts`.\n */\nimport { Command } from 'commander';\nimport { promises as fs } from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { catalog } from '@ddt-tools/core';\n\nexport interface SearchMatch {\n profile: string;\n fqn: string;\n objectType: string;\n}\n\nexport interface SearchResult {\n profile: string;\n matches: SearchMatch[];\n error?: string;\n}\n\nexport interface SearchFnOptions {\n exact: boolean;\n objectType?: string;\n /** Project / cache root. Defaults to `process.cwd()`. */\n root?: string;\n}\n\nexport type SearchFn = (\n profile: string,\n pattern: string,\n opts: SearchFnOptions,\n) => Promise<SearchMatch[]>;\n\nfunction buildDriftReport(results: SearchResult[]): string {\n const allFqns = new Set<string>();\n const byFqn = new Map<string, Set<string>>();\n for (const r of results) {\n if (r.error) continue;\n for (const m of r.matches) {\n allFqns.add(m.fqn);\n if (!byFqn.has(m.fqn)) byFqn.set(m.fqn, new Set());\n byFqn.get(m.fqn)!.add(r.profile);\n }\n }\n const successProfiles = results.filter((r) => !r.error).map((r) => r.profile);\n const driftLines: string[] = [];\n for (const fqn of allFqns) {\n const present = byFqn.get(fqn)!;\n if (present.size < successProfiles.length) {\n const absent = successProfiles.filter((p) => !present.has(p));\n driftLines.push(\n ` DRIFT ${fqn} [present: ${[...present].join(', ')} absent: ${absent.join(', ')}]`,\n );\n }\n }\n return driftLines.join('\\n');\n}\n\nfunction renderText(results: SearchResult[], showDrift: boolean): string {\n const lines: string[] = [];\n for (const r of results) {\n if (r.error) {\n lines.push(`[${r.profile}] ERROR: ${r.error}`);\n continue;\n }\n if (r.matches.length === 0) {\n lines.push(`[${r.profile}] no matches`);\n } else {\n for (const m of r.matches) {\n lines.push(`[${r.profile}] ${m.fqn} (${m.objectType})`);\n }\n }\n }\n if (showDrift) {\n const drift = buildDriftReport(results);\n if (drift) {\n lines.push('');\n lines.push('--- Drift detected ---');\n lines.push(drift);\n }\n }\n return lines.join('\\n');\n}\n\nasync function loadProfileNames(profilesOpt: string, profilesDir: string): Promise<string[]> {\n if (profilesOpt.toLowerCase() !== 'all') {\n return profilesOpt\n .split(',')\n .map((p) => p.trim())\n .filter(Boolean);\n }\n try {\n const entries = await fs.readdir(profilesDir);\n return entries\n .filter((e) => e.endsWith('.json') || e.endsWith('.toml'))\n .map((e) => path.basename(e, path.extname(e)));\n } catch {\n return [];\n }\n}\n\n/**\n * Wire to the on-disk catalog cache (`<root>/.ddt/cache/<profile>/catalog.msgpack`\n * written by `ddt catalog refresh` / `ddt extract --write-catalog-cache`).\n *\n * 1. Open `catalog.CatalogCache({root, connection: profile})`.\n * 2. Read the snapshot — `get()` returns an empty snapshot when the\n * file is absent / corrupt / version-mismatched.\n * 3. If the snapshot is empty, surface an actionable error naming\n * the expected file path and the two commands that populate it.\n * 4. Walk every (catalog, schema, object), filter by `--type`, then\n * match the name (case-insensitive substring by default, exact\n * when `--exact` is set), and return `SearchMatch[]` with the\n * fully-qualified `catalog.schema.name`.\n *\n * Injectable for tests via the `searchFn` parameter on `searchCommand`.\n */\nasync function defaultSearchFn(\n profile: string,\n pattern: string,\n opts: SearchFnOptions,\n): Promise<SearchMatch[]> {\n const root = opts.root ?? process.cwd();\n const cache = new catalog.CatalogCache({ root, connection: profile });\n const snapshot = await cache.get();\n if (snapshot.catalogs.length === 0) {\n throw new Error(\n `No catalog cache for profile \"${profile}\" at ${cache.path}. ` +\n `Run \\`ddt catalog refresh --connection ${profile} --root ${root}\\` ` +\n `or \\`ddt extract --connection ${profile} --output ${root} --write-catalog-cache\\` first.`,\n );\n }\n const needle = pattern.toLowerCase();\n const typeFilter = opts.objectType ? opts.objectType.toUpperCase() : undefined;\n const matches: SearchMatch[] = [];\n for (const cat of snapshot.catalogs) {\n for (const schema of cat.schemas) {\n for (const obj of schema.objects) {\n if (typeFilter && obj.objectType !== typeFilter) continue;\n const name = obj.name.toLowerCase();\n const hit = opts.exact ? name === needle : name.includes(needle);\n if (hit) {\n matches.push({\n profile,\n fqn: `${obj.catalog}.${obj.schema}.${obj.name}`,\n objectType: obj.objectType,\n });\n }\n }\n }\n }\n return matches;\n}\n\nexport function searchCommand(searchFn: SearchFn = defaultSearchFn): Command {\n const cmd = new Command('search');\n cmd\n .description('Find objects matching a name pattern across one or more connection profiles.')\n .argument('<pattern>', 'Name pattern to search for (case-insensitive substring).')\n .requiredOption(\n '--profiles <list|all>',\n 'Comma-separated profile names, or \"all\" to scan every configured profile.',\n )\n .option('--exact', 'Exact name match instead of substring.', false)\n .option('--type <objectType>', 'Filter results to a specific object type (e.g. TABLE, VIEW).')\n .option('--format <fmt>', 'text | json (default text).', 'text')\n .option(\n '--profiles-dir <dir>',\n 'Directory to scan when --profiles all is used.',\n path.join(os.homedir(), '.ddt', 'connections'),\n )\n .option(\n '--root <dir>',\n 'Project / cache root containing the .ddt/cache directory. Default: cwd.',\n process.cwd(),\n )\n .option('--no-drift', 'Suppress the drift section in text output.')\n .action(async (pattern: string, opts) => {\n const profiles = await loadProfileNames(opts.profiles as string, opts.profilesDir as string);\n if (profiles.length === 0) {\n throw new Error(\n opts.profiles.toLowerCase() === 'all'\n ? `No profiles found in ${opts.profilesDir}. Run \\`ddt connection add\\` first.`\n : '--profiles must list at least one profile.',\n );\n }\n\n const results: SearchResult[] = await Promise.all(\n profiles.map(async (p) => {\n try {\n const matches = await searchFn(p, pattern, {\n exact: opts.exact as boolean,\n objectType: opts.type as string | undefined,\n root: opts.root as string,\n });\n return { profile: p, matches };\n } catch (err) {\n return {\n profile: p,\n matches: [],\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }),\n );\n\n const fmt = String(opts.format ?? 'text').toLowerCase();\n if (fmt === 'json') {\n process.stdout.write(JSON.stringify(results, null, 2) + '\\n');\n return;\n }\n if (fmt !== 'text') throw new Error(`Unknown --format: ${opts.format}. Use text | json.`);\n const text = renderText(results, opts.drift !== false);\n process.stdout.write(text ? text + '\\n' : 'No results.\\n');\n });\n return cmd;\n}\n","/**\n * `ddt query-log` — AUTH.5 local query log CLI.\n *\n * Subcommands:\n * ddt query-log list [--profile <p>] [--limit N] [--format text|json]\n * ddt query-log show <id> [--format text|json|sql]\n * ddt query-log add <sql> --profile <p> [--status success|error] [--store <path>]\n * ddt query-log clear [--profile <p>] [--yes]\n *\n * The log is stored at `~/.ddt/query-log.json` (override with --store).\n * EE3 will call `appendEntry()` on the substrate directly when a query\n * is executed. This CLI surfaces it for ad-hoc review + rerun.\n *\n * Mirrors `Snowflake/packages/cli/src/commands/query-log.ts`.\n */\nimport { Command } from 'commander';\nimport { promises as fs } from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { queryLog } from '@ddt-tools/core';\n\nconst DEFAULT_STORE = path.join(os.homedir(), '.ddt', 'query-log.json');\n\nasync function loadStore(storePath: string): Promise<queryLog.QueryLogStore> {\n try {\n const raw = await fs.readFile(storePath, 'utf8');\n return queryLog.QueryLogStore.deserialize(JSON.parse(raw));\n } catch {\n return new queryLog.QueryLogStore();\n }\n}\n\nasync function saveStore(storePath: string, store: queryLog.QueryLogStore): Promise<void> {\n await fs.mkdir(path.dirname(storePath), { recursive: true });\n await fs.writeFile(storePath, JSON.stringify(store.serialize(), null, 2), 'utf8');\n}\n\nexport function queryLogCommand(): Command {\n const cmd = new Command('query-log');\n cmd.description('Browse and manage the local query log from the EE3 query window (AUTH.5).');\n\n cmd\n .command('list')\n .description('List recent query log entries (newest first).')\n .option('--profile <p>', 'Filter to a specific connection profile.')\n .option('--limit <n>', 'Maximum entries to show (default 100).', '100')\n .option('--format <fmt>', 'text | json (default text).', 'text')\n .option('--store <path>', 'Path to the query log JSON file.', DEFAULT_STORE)\n .action(async (opts) => {\n const store = await loadStore(opts.store as string);\n const entries = store.listEntries({\n profile: opts.profile as string | undefined,\n limit: parseInt(String(opts.limit ?? '100'), 10),\n });\n const fmt = String(opts.format ?? 'text').toLowerCase();\n if (fmt === 'json') {\n process.stdout.write(JSON.stringify(entries, null, 2) + '\\n');\n return;\n }\n if (entries.length === 0) {\n process.stdout.write('No query log entries.\\n');\n return;\n }\n for (const e of entries) {\n const when = e.executedAt.slice(0, 19).replace('T', ' ');\n const dur = e.durationMs !== undefined ? ` ${e.durationMs}ms` : '';\n const rows = e.rowCount !== undefined ? ` ${e.rowCount} rows` : '';\n const status = e.status === 'error' ? ' ✗' : ' ✓';\n const sql = e.sql.replace(/\\s+/g, ' ').slice(0, 80);\n process.stdout.write(`[${e.id}] ${when} [${e.profile}]${status}${dur}${rows} ${sql}\\n`);\n }\n });\n\n cmd\n .command('show <id>')\n .description('Show a single query log entry by id.')\n .option('--format <fmt>', 'text | json | sql (default text).', 'text')\n .option('--store <path>', 'Path to the query log JSON file.', DEFAULT_STORE)\n .action(async (id: string, opts) => {\n const store = await loadStore(opts.store as string);\n const entry = store.getEntry(id);\n if (!entry) throw new Error(`No entry with id '${id}'.`);\n const fmt = String(opts.format ?? 'text').toLowerCase();\n if (fmt === 'sql') {\n process.stdout.write(entry.sql + '\\n');\n return;\n }\n if (fmt === 'json') {\n process.stdout.write(JSON.stringify(entry, null, 2) + '\\n');\n return;\n }\n process.stdout.write(`id: ${entry.id}\\n`);\n process.stdout.write(`profile: ${entry.profile}\\n`);\n process.stdout.write(`executed: ${entry.executedAt}\\n`);\n process.stdout.write(`status: ${entry.status}\\n`);\n if (entry.durationMs !== undefined) process.stdout.write(`duration: ${entry.durationMs}ms\\n`);\n if (entry.rowCount !== undefined) process.stdout.write(`rows: ${entry.rowCount}\\n`);\n if (entry.error) process.stdout.write(`error: ${entry.error}\\n`);\n process.stdout.write(`\\n${entry.sql}\\n`);\n });\n\n cmd\n .command('add <sql>')\n .description('Manually append a query to the log (used by EE3 and for testing).')\n .requiredOption('--profile <p>', 'Connection profile the query was run against.')\n .option('--status <s>', 'success | error (default success).', 'success')\n .option('--store <path>', 'Path to the query log JSON file.', DEFAULT_STORE)\n .action(async (sql: string, opts) => {\n if (opts.status !== 'success' && opts.status !== 'error') {\n throw new Error(`--status must be success or error, got: ${opts.status}`);\n }\n const store = await loadStore(opts.store as string);\n const entry = store.appendEntry({\n profile: opts.profile as string,\n sql,\n executedAt: new Date().toISOString(),\n status: opts.status as 'success' | 'error',\n });\n await saveStore(opts.store as string, store);\n process.stdout.write(`Added entry ${entry.id}.\\n`);\n });\n\n cmd\n .command('clear')\n .description('Remove query log entries.')\n .option('--profile <p>', 'Remove only entries for this profile (omit for all).')\n .option('--yes', 'Skip confirmation prompt.')\n .option('--store <path>', 'Path to the query log JSON file.', DEFAULT_STORE)\n .action(async (opts) => {\n if (!opts.yes) {\n const target = opts.profile ? `profile '${opts.profile as string}'` : 'all profiles';\n throw new Error(`Pass --yes to confirm clearing the query log for ${target}.`);\n }\n const store = await loadStore(opts.store as string);\n const removed = store.clearEntries(opts.profile as string | undefined);\n await saveStore(opts.store as string, store);\n process.stdout.write(`Cleared ${removed} entries.\\n`);\n });\n\n return cmd;\n}\n","/**\n * `ddt savings` — display estimated AI token savings accumulated by using\n * deterministic DDT surfaces instead of LLM calls.\n *\n * DSC.8: token-savings counter CLI.\n *\n * $ ddt savings\n * $ ddt savings --format json\n * $ ddt savings --top 5\n * $ ddt savings --reset\n *\n * Persistence: `~/.ddt/token-savings.json` (override with `--store <path>`).\n * The substrate (`@ddt-tools/core TokenSavingsCounter`) is pure in-memory; this\n * file is the disk-I/O boundary.\n *\n * Mirrors `Snowflake/packages/cli/src/commands/savings.ts`.\n */\nimport { promises as fs } from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { discovery } from '@ddt-tools/core';\nimport chalk from 'chalk';\n\nconst DEFAULT_STORE = path.join(os.homedir(), '.ddt', 'token-savings.json');\n\nasync function loadCounter(storePath: string): Promise<discovery.TokenSavingsCounter> {\n try {\n const raw = await fs.readFile(storePath, 'utf8');\n return discovery.TokenSavingsCounter.deserialize(JSON.parse(raw) as unknown);\n } catch {\n return new discovery.TokenSavingsCounter();\n }\n}\n\nasync function saveCounter(\n storePath: string,\n counter: discovery.TokenSavingsCounter,\n): Promise<void> {\n await fs.mkdir(path.dirname(storePath), { recursive: true });\n await fs.writeFile(storePath, JSON.stringify(counter.serialize(), null, 2) + '\\n', 'utf8');\n}\n\nexport function savingsCommand(): Command {\n const cmd = new Command('savings');\n cmd\n .description('Show estimated AI token savings from using deterministic DDT surfaces.')\n .option('--store <path>', 'Override the savings JSON store path.', DEFAULT_STORE)\n .option('--format <fmt>', 'Output format: text | json.', 'text')\n .option('--top <n>', 'Show top N channels by tokens saved (text format only).', '5')\n .option('--reset', 'Clear all recorded savings and exit.')\n .action(async (opts) => {\n const storePath = String(opts.store ?? DEFAULT_STORE);\n const fmt = String(opts.format ?? 'text').toLowerCase();\n const topN = Math.max(1, Math.floor(parseInt(String(opts.top ?? '5'), 10) || 5));\n\n if (opts.reset) {\n const counter = new discovery.TokenSavingsCounter();\n await saveCounter(storePath, counter);\n process.stdout.write(chalk.green('✅ Savings counter reset.\\n'));\n return;\n }\n\n const counter = await loadCounter(storePath);\n const summary = counter.summary();\n\n if (fmt === 'json') {\n const weeks = counter.summarizeByWeek();\n const top = counter.topChannels(topN);\n process.stdout.write(\n JSON.stringify({ summary, weeklyBreakdown: weeks, topChannels: top }, null, 2) + '\\n',\n );\n return;\n }\n\n if (summary.eventCount === 0) {\n process.stdout.write(\n chalk.dim(\n ' No savings recorded yet.\\n' +\n ' DDT records a saving every time you use explain, discover, lineage, or similar\\n' +\n ' deterministic surfaces instead of asking an AI.\\n',\n ),\n );\n return;\n }\n\n const thousands = (n: number): string =>\n n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n);\n\n process.stdout.write('\\n');\n process.stdout.write(\n chalk.bold(` ${thousands(summary.totalTokens)} tokens saved`) +\n chalk.dim(` across ${summary.eventCount} interactions`) +\n '\\n',\n );\n if (summary.sinceFirst) {\n process.stdout.write(chalk.dim(` Tracking since ${summary.sinceFirst.slice(0, 10)}\\n`));\n }\n process.stdout.write('\\n');\n\n const top = counter.topChannels(topN);\n if (top.length > 0) {\n process.stdout.write(chalk.dim(' Top surfaces:\\n'));\n for (const { channel, tokens } of top) {\n process.stdout.write(\n ` ${chalk.cyan(channel.padEnd(28))}${thousands(tokens)} tokens\\n`,\n );\n }\n process.stdout.write('\\n');\n }\n\n const weeks = counter.summarizeByWeek().slice(0, 4);\n if (weeks.length > 0) {\n process.stdout.write(chalk.dim(' Weekly:\\n'));\n for (const bucket of weeks) {\n process.stdout.write(\n ` ${chalk.dim(bucket.week.padEnd(10))}${thousands(bucket.tokens)} tokens\\n`,\n );\n }\n process.stdout.write('\\n');\n }\n\n process.stdout.write(\n chalk.dim(` Store: ${storePath}\\n`) +\n chalk.dim(' ddt savings --reset · ddt savings --format json\\n'),\n );\n });\n\n return cmd;\n}\n","/**\n * `ddt trial start|status|reset` — manage the local 30-day Pro trial.\n * Mirrors `sdt trial` in shape (PIL.1 + PIL.4).\n */\nimport { Command } from 'commander';\nimport { license } from '@ddt-tools/core';\nimport { logger } from '../util/logger.js';\n\nexport function trialCommand(): Command {\n const cmd = new Command('trial').description(\n 'Manage the DDT 30-day Pro trial (no account required).',\n );\n\n cmd\n .command('start')\n .description('Begin a 30-day Pro trial.')\n .action(async () => {\n const record = await license.startTrial();\n logger.info(`Pro trial started. Expires on ${record.expiresAt.slice(0, 10)}.`);\n logger.info('Run `ddt trial status` to check remaining time.');\n });\n\n cmd\n .command('status')\n .description('Show current trial state.')\n .action(async () => {\n const status = await license.getTrialStatus();\n logger.info(license.describeTrialStatus(status));\n });\n\n cmd\n .command('reset')\n .description('Reset trial state (dev/test only — requires DDT_DEV_RESET_TRIAL=1).')\n .action(async () => {\n await license.resetTrial();\n logger.info('Trial state cleared.');\n });\n\n return cmd;\n}\n","/**\n * `ddt pilot register|status` — manage pilot program registration.\n * Mirrors `sdt pilot` in shape (PIL.2).\n */\nimport { Command } from 'commander';\nimport { license } from '@ddt-tools/core';\nimport { logger } from '../util/logger.js';\n\nexport function pilotCommand(): Command {\n const cmd = new Command('pilot').description(\n 'Join or check the DDT pilot program (90-day Pro access for early adopters).',\n );\n\n cmd\n .command('register')\n .description('Register for the DDT pilot program.')\n .requiredOption('--email <addr>', 'Your email address.')\n .action(async (opts: { email: string }) => {\n logger.info('Registering for the DDT pilot program…');\n const meta = await license.registerPilot(opts.email);\n logger.info(`Registered! Email: ${meta.email}`);\n logger.info('Your pilot JWT has been stored at ~/.ddt/license.jwt.');\n logger.info('Run `ddt pilot status` to confirm.');\n });\n\n cmd\n .command('status')\n .description('Show pilot program registration status.')\n .action(async () => {\n const status = await license.getPilotStatus();\n logger.info(license.describePilotStatus(status));\n });\n\n return cmd;\n}\n","/**\n * CLI error-reporting wiring (ERR.2).\n *\n * Lazily imported from `cli.ts` hooks so the cold-start path pays zero cost\n * until a command actually runs (preAction) or fails (catch handler).\n *\n * Responsibilities:\n * - first-run consent prompt (TTY only, default Yes, one keystroke)\n * - crash-hook installation when consent allows capture\n * - end-of-run drain: spool → `POST /errors` when consent is `on`\n * - manual \"Report this error? [y/N]\" prompt when consent is NOT `on`\n * and a command fails\n *\n * @see @ddt-tools/core/errorReport (capture substrate + consent + transport)\n */\nimport { createInterface } from 'node:readline';\n// Subpath import, NOT the `@ddt-tools/core` barrel — this module runs in the\n// preAction hook of every command; the barrel would drag ~85 core modules in.\nimport * as errorReport from '@ddt-tools/core/errorReport';\nimport { logger } from './logger.js';\n\n/** Commands that must never trigger the consent prompt or auto-drain. */\nconst EXEMPT_COMMANDS = new Set(['telemetry', 'feedback', 'help', 'completion']);\n\nlet activeConsent: errorReport.ErrorReportConsent = 'unset';\nlet uninstallHooks: (() => void) | null = null;\n\n/**\n * preAction hook body. Reads (and on first run, prompts for) consent, then\n * installs crash capture unless the user opted out.\n */\nexport async function setupErrorReporting(commandName: string): Promise<void> {\n if (EXEMPT_COMMANDS.has(commandName)) return;\n const stored = await errorReport.readConsent();\n activeConsent = stored.consent;\n\n // First-run consent prompt — explicit, one keystroke, default Yes.\n // Skipped when not interactive (CI, pipes) so scripted runs never block.\n if (\n shouldPromptFirstRun(stored.consent) &&\n process.stdout.isTTY &&\n process.stdin.isTTY &&\n !isCi()\n ) {\n // Beta install-time messaging — shown ONCE, immediately before the very\n // first consent question (true first run, consent still `unset`).\n printBetaNotice();\n activeConsent = (await promptFirstRunConsent()) ? 'on' : 'off';\n await errorReport.writeConsent(activeConsent === 'on' ? 'on' : 'off');\n }\n\n // Crash capture is installed unless the user said no. Capture is local-only;\n // nothing leaves the machine without `isErrorReportingEnabled` saying so.\n if (activeConsent !== 'off') {\n uninstallHooks = errorReport.installProcessHooks();\n }\n}\n\n/**\n * postAction hook body. Flushes buffered events and, when consent is `on`,\n * drains the spool to the Worker. No-ops fast when there is nothing to send.\n * `transport` is injectable for tests.\n */\nexport async function finishErrorReporting(\n productVersion: string,\n transport: errorReport.TransportOptions = {},\n): Promise<void> {\n await errorReport.flushErrorEvents();\n\n // Anonymous usage ping (opt-in) — gated internally by the SAME consent +\n // env opt-outs as error reporting and throttled to once per 24h. It is\n // awaited here (not detached) so the postAction lifecycle has a\n // deterministic completion point: `sendUsagePing` is self-bounded (3s hard\n // timeout) and never throws, so awaiting it can block command exit by at\n // most that timeout — the same bound the spool drain below already imposes.\n // Detaching it left the send racing process teardown, which both dropped\n // pings in practice and made the wiring untestable without a sleep.\n // `transport.fetchImpl` is threaded through so tests can intercept it.\n await errorReport\n .sendUsagePing({\n product: 'ddt',\n version: productVersion,\n surface: 'cli',\n ...(transport.fetchImpl ? { fetchImpl: transport.fetchImpl } : {}),\n })\n .catch(() => undefined);\n\n if (!errorReport.isErrorReportingEnabled(activeConsent)) return;\n const spooled = await errorReport.listSpooled(transport.dir);\n if (spooled.length === 0) return;\n const result = await errorReport.drainSpool({ productVersion }, transport);\n if (result.sent > 0) {\n logger.dim(` (${result.sent} error report${result.sent === 1 ? '' : 's'} sent — thank you)`);\n }\n}\n\n/**\n * Top-level command-failure handler. Reports the error as `handled` (real\n * crashes go through `uncaughtExceptionMonitor`), then either auto-sends\n * (consent `on`) or offers a one-keystroke manual report.\n * `transport` is injectable for tests.\n */\nexport async function reportCliFailure(\n err: unknown,\n productVersion: string,\n transport: errorReport.TransportOptions = {},\n): Promise<void> {\n errorReport.reportError(err, 'handled', 'cli:main');\n await errorReport.flushErrorEvents(transport.dir);\n\n if (errorReport.isErrorReportingEnabled(activeConsent)) {\n await errorReport.drainSpool({ productVersion }, transport);\n return;\n }\n\n // Manual push path — only when interactive.\n if (!process.stdout.isTTY || !process.stdin.isTTY || isCi()) return;\n const yes = await promptYesNo('Report this error to the DDT team? [y/N] ', false);\n if (!yes) return;\n const result = await errorReport.drainSpool({ productVersion }, transport);\n if (result.sent > 0) logger.dim(' Report sent — thank you.');\n else logger.dim(' Could not reach the error endpoint; the report is queued locally.');\n}\n\n/** Uninstall crash hooks (tests). */\nexport function teardownErrorReporting(): void {\n uninstallHooks?.();\n uninstallHooks = null;\n activeConsent = 'unset';\n}\n\n/** Current consent as seen by the hooks (tests). */\nexport function activeConsentForTests(): errorReport.ErrorReportConsent {\n return activeConsent;\n}\n\n/** DDT version surfaced in the first-run beta notice. */\nconst BETA_VERSION = '0.2.0';\n\n/**\n * Whether the first-run flow (beta notice + consent prompt) should fire.\n * True ONLY on true first run — when consent has never been decided\n * (`unset`). Exported so the \"first run only\" contract is unit-testable\n * without faking a TTY.\n */\nexport function shouldPromptFirstRun(consent: errorReport.ErrorReportConsent): boolean {\n return consent === 'unset';\n}\n\n/**\n * Beta install-time messaging — printed ONCE, on true first run (consent\n * `unset`), immediately before the consent question. Tells the user, at\n * install time: it's a 30-day public beta with all features free; what\n * happens after the beta (core stays free forever, Pro features keep\n * working but show license notices); that AI features are bring-your-own\n * key; and how to report a bug. Plain ASCII box to match CLI output style.\n */\nexport function printBetaNotice(): void {\n const lines = [\n '┌─────────────────────────────────────────────────────────┐',\n `│ DDT ${BETA_VERSION} — Public Beta │`,\n '│ • All features are free during the beta. │',\n '│ • After the beta: core features stay free forever; │',\n '│ Pro features keep working and show license notices. │',\n '│ • AI features use your own API key (never ours). │',\n '│ • Found a bug? Run: ddt feedback \"<what happened>\" │',\n '└─────────────────────────────────────────────────────────┘',\n ];\n for (const line of lines) logger.info(line);\n}\n\nasync function promptFirstRunConsent(): Promise<boolean> {\n logger.info('DDT can report errors automatically (sanitized diagnostics + OS context,');\n logger.info('never your SQL, identifiers, or credentials) so they get fixed fast.');\n logger.info(errorReport.CONSENT_WARNING);\n return promptYesNo('Enable automatic error reporting? [Y/n] ', true);\n}\n\nfunction promptYesNo(question: string, defaultYes: boolean): Promise<boolean> {\n return new Promise((resolve) => {\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n rl.question(question, (answer) => {\n rl.close();\n const normalized = answer.trim().toLowerCase();\n if (normalized === '') resolve(defaultYes);\n else resolve(normalized === 'y' || normalized === 'yes');\n });\n });\n}\n\nfunction isCi(): boolean {\n return process.env['CI'] === 'true';\n}\n","#!/usr/bin/env node\n/**\n * `ddt` — Databricks Data Tools command-line interface.\n *\n * Mirrors the SDT CLI surface: every command name and flag matches so muscle\n * memory carries between Snowflake and Databricks engagements.\n *\n * Subcommand modules are loaded LAZILY: only the requested subcommand's\n * module (and its `@ddt-tools/core` dependency chain) is imported on the common\n * path. `--help` / `--version` / no-arg / unknown-command paths fall back\n * to loading every command so Commander can render the full subcommand\n * list.\n *\n * Cold-start win: `ddt <known-cmd> ...` skips ~80 command-module loads\n * and their per-module `@ddt-tools/core/...` imports. Mirrors the SDT-side\n * pattern; see Snowflake/packages/cli/src/cli.ts.\n */\nimport { Command } from 'commander';\nimport { FeatureAdvisor, DDT_HINT_RULES } from '@ddt-tools/core/discovery';\n// Subpath imports, NOT the `@ddt-tools/core` barrel — the barrel statically pulls\n// every core module (~85) and was the dominant cold-start cost (RH3.3).\nimport * as outputStyle from '@ddt-tools/core/outputStyle';\nimport * as featuresNs from '@ddt-tools/core/features';\nimport chalk from 'chalk';\n\n// Cold-start timestamp for `ddt perf cold-start`. ESM hoists imports above\n// this line, so a plain `process.hrtime.bigint()` here would EXCLUDE the\n// import cost from the measurement. Back-date the stamp to true process\n// start (`performance.now()` counts from process timeOrigin) so the\n// reported number covers Node bootstrap + ESM imports + command dispatch.\n// `??=` preserves a value pre-set by any earlier bootstrap wrapper.\n(globalThis as { __DDT_START_NS__?: bigint }).__DDT_START_NS__ ??=\n process.hrtime.bigint() - BigInt(Math.round(performance.now() * 1e6));\n\n// Mapping of CLI subcommand-name → lazy loader. Each loader resolves to\n// the Commander `Command` instance for that subcommand. When you add a\n// new top-level `ddt <name>` command, add its entry here. Aliases (`erd`)\n// can re-use the same module export with a different factory name.\nconst COMMAND_LOADERS: Record<string, () => Promise<Command>> = {\n connection: async () => (await import('./commands/connection.js')).connectionCommand(),\n init: async () => (await import('./commands/init.js')).initCommand(),\n validate: async () => (await import('./commands/validate.js')).validateCommand(),\n compare: async () => (await import('./commands/compare.js')).compareCommand(),\n build: async () => (await import('./commands/build.js')).buildCommand(),\n publish: async () => (await import('./commands/publish.js')).publishCommand(),\n script: async () => (await import('./commands/script.js')).scriptCommand(),\n import: async () => (await import('./commands/import.js')).importCommand(),\n extract: async () => (await import('./commands/extract.js')).extractCommand(),\n completion: async () => (await import('./commands/completion.js')).completionCommand(),\n drift: async () => (await import('./commands/drift.js')).driftCommand(),\n format: async () => (await import('./commands/format.js')).formatCommand(),\n lint: async () => (await import('./commands/lint.js')).lintCommand(),\n docs: async () => (await import('./commands/docs.js')).docsCommand(),\n erd: async () => (await import('./commands/docs.js')).erdCommand(),\n verify: async () => (await import('./commands/verify.js')).verifyCommand(),\n revert: async () => (await import('./commands/revert.js')).revertCommand(),\n snapshot: async () => (await import('./commands/snapshot.js')).snapshotCommand(),\n graph: async () => (await import('./commands/graph.js')).graphCommand(),\n lineage: async () => (await import('./commands/lineage.js')).lineageCommand(),\n diagnose: async () => (await import('./commands/diagnose.js')).diagnoseCommand(),\n review: async () => (await import('./commands/review.js')).reviewCommand(),\n impact: async () => (await import('./commands/impact.js')).impactCommand(),\n 'cost-estimate': async () => (await import('./commands/cost-estimate.js')).costEstimateCommand(),\n 'pr-comment': async () => (await import('./commands/pr-comment.js')).prCommentCommand(),\n template: async () => (await import('./commands/template.js')).templateCommand(),\n anonymize: async () => (await import('./commands/anonymize.js')).anonymizeCommand(),\n test: async () => (await import('./commands/test.js')).testCommand(),\n branch: async () => (await import('./commands/branch.js')).branchCommand(),\n schema: async () => (await import('./commands/schema.js')).schemaCommand(),\n suggest: async () => (await import('./commands/suggest.js')).suggestCommand(),\n history: async () => (await import('./commands/history.js')).historyCommand(),\n 'audit-log': async () => (await import('./commands/audit-log.js')).auditLogCommand(),\n 'install-hooks': async () => (await import('./commands/install-hooks.js')).installHooksCommand(),\n telemetry: async () => (await import('./commands/telemetry.js')).telemetryCommand(),\n seed: async () => (await import('./commands/seed.js')).seedCommand(),\n suite: async () => (await import('./commands/suite.js')).suiteCommand(),\n refactor: async () => (await import('./commands/refactor.js')).refactorCommand(),\n license: async () => (await import('./commands/license.js')).licenseCommand(),\n mcp: async () => (await import('./commands/mcp.js')).mcpCommand(),\n ai: async () => (await import('./commands/ai.js')).aiCommand(),\n explain: async () => (await import('./commands/explain.js')).explainCommand(),\n feedback: async () => (await import('./commands/feedback.js')).feedbackCommand(),\n features: async () => (await import('./commands/features.js')).featuresCommand(),\n hosts: async () => (await import('./commands/hosts.js')).hostsCommand(),\n safety: async () => (await import('./commands/safety.js')).safetyCommand(),\n pii: async () => (await import('./commands/pii.js')).piiCommand(),\n bisect: async () => (await import('./commands/bisect.js')).bisectCommand(),\n changelog: async () => (await import('./commands/changelog.js')).changelogCommand(),\n replay: async () => (await import('./commands/replay.js')).replayCommand(),\n 'drift-gate': async () => (await import('./commands/drift-gate.js')).driftGateCommand(),\n promote: async () => (await import('./commands/promote.js')).promoteCommand(),\n 'data-fit': async () => (await import('./commands/data-fit.js')).dataFitCommand(),\n 'data-compare': async () => (await import('./commands/data-compare.js')).dataCompareCommand(),\n approval: async () => (await import('./commands/approval.js')).approvalCommand(),\n 'advise-tests': async () => (await import('./commands/advise-tests.js')).adviseTestsCommand(),\n 'safer-alternative': async () =>\n (await import('./commands/safer-alternative.js')).saferAlternativeCommand(),\n sketch: async () => (await import('./commands/sketch.js')).sketchCommand(),\n design: async () => (await import('./commands/design.js')).designCommand(),\n optimize: async () => (await import('./commands/optimize.js')).optimizeCommand(),\n 'rollback-suggest': async () =>\n (await import('./commands/rollback-suggest.js')).rollbackSuggestCommand(),\n 'compare-profiles': async () =>\n (await import('./commands/compare-profiles.js')).compareProfilesCommand(),\n explorer: async () => (await import('./commands/explorer.js')).explorerCommand(),\n catalog: async () => (await import('./commands/catalog.js')).catalogCommand(),\n 'xcompare-ir': async () => (await import('./commands/xcompare.js')).xcompareCommand(),\n profile: async () => (await import('./commands/profile.js')).profileCommand(),\n 'suggest-constraints': async () =>\n (await import('./commands/suggest-constraints.js')).suggestConstraintsCommand(),\n purge: async () => (await import('./commands/purge.js')).purgeCommand(),\n preview: async () => (await import('./commands/preview.js')).previewCommand(),\n refresh: async () => (await import('./commands/refresh.js')).refreshCommand(),\n discover: async () => (await import('./commands/discover.js')).discoverCommand(),\n find: async () => (await import('./commands/find.js')).findCommand(),\n 'scan-secrets': async () => (await import('./commands/scan-secrets.js')).scanSecretsCommand(),\n 'error-lookup': async () => (await import('./commands/error-lookup.js')).errorLookupCommand(),\n 'deploy-status': async () => (await import('./commands/deploy-status.js')).deployStatusCommand(),\n 'approval-chain': async () =>\n (await import('./commands/approval-chain.js')).approvalChainCommand(),\n standards: async () => (await import('./commands/standards.js')).standardsCommand(),\n perf: async () => (await import('./commands/perf.js')).perfCommand(),\n 'migrate-platform': async () =>\n (await import('./commands/migrate-platform.js')).migratePlatformCommand(),\n migrate: async () => (await import('./commands/migrate-from-dbt.js')).migrateFromDbtCommand(),\n backlog: async () => (await import('./commands/backlog.js')).backlogCommand(),\n watch: async () => (await import('./commands/watch.js')).watchCommand(),\n bookmarks: async () => (await import('./commands/bookmarks.js')).bookmarksCommand(),\n snippets: async () => (await import('./commands/snippets.js')).snippetsCommand(),\n generate: async () => (await import('./commands/generate.js')).generateCommand(),\n exec: async () => (await import('./commands/exec.js')).execCommand(),\n search: async () => (await import('./commands/search.js')).searchCommand(),\n 'query-log': async () => (await import('./commands/query-log.js')).queryLogCommand(),\n savings: async () => (await import('./commands/savings.js')).savingsCommand(),\n trial: async () => (await import('./commands/trial.js')).trialCommand(),\n pilot: async () => (await import('./commands/pilot.js')).pilotCommand(),\n};\n\nasync function main(): Promise<void> {\n const program = new Command();\n program\n .name('ddt')\n .description(\n 'Databricks Data Tools — declarative schema management for Databricks Unity Catalog.',\n )\n .version('0.2.0', '-v, --version')\n .option(\n '--style <mode>',\n 'Output style: standard | audit | ci | review | terse. Also reads DDT_OUTPUT_STYLE env var.',\n outputStyle.resolveOutputStyle(),\n )\n .option('--explain-features', 'After each command, show related features from the catalog.');\n\n const arg2 = process.argv[2];\n const explicitLoader = arg2 && !arg2.startsWith('-') ? COMMAND_LOADERS[arg2] : undefined;\n\n if (explicitLoader) {\n program.addCommand(await explicitLoader());\n } else {\n const cmds = await Promise.all(Object.values(COMMAND_LOADERS).map((load) => load()));\n for (const c of cmds) program.addCommand(c);\n }\n\n // Global help footer — surfaces the searchable options catalog\n // (`ddt explain <query>`) on every command's --help screen. Free-tier\n // discoverability hook: users land in --help, see the hint, learn\n // they can ask `ddt explain allowDropTable` for safety + path detail\n // without leaving the terminal. Mirrors the SDT-side footer.\n program.addHelpText('afterAll', () =>\n [\n '',\n 'Options catalog:',\n ' Every CLI flag and `.ddtproj` option has a searchable entry with safety',\n ' tier, default, related options, and an example. Look one up with:',\n ' ddt explain <name> # e.g. ddt explain allowDropTable',\n ' ddt explain <topic> # fuzzy: \"drop\", \"safety\", \"compare\"',\n '',\n 'Features catalog (locked + unlocked):',\n ' ddt features list # what ships in each tier',\n ' ddt features show <id>',\n '',\n 'Personalized suggestions:',\n ' ddt discover # feature tips based on your usage history',\n '',\n ].join('\\n'),\n );\n\n // ERR.2 — error-reporting lifecycle. Lazily imported so the cold-start\n // path pays nothing; the preAction hook handles first-run consent +\n // crash-hook install, the postAction hook drains the spool when consent\n // is on. Both no-op fast for exempt commands (telemetry, feedback, help).\n program.hook('preAction', async (_thisCommand, actionCommand) => {\n if (actionCommand.parent !== program) return;\n const reporting = await import('./util/errorReporting.js');\n await reporting.setupErrorReporting(actionCommand.name());\n });\n program.hook('postAction', async (_thisCommand, actionCommand) => {\n if (actionCommand.parent !== program) return;\n const reporting = await import('./util/errorReporting.js');\n await reporting.finishErrorReporting('0.2.0');\n });\n\n // Feature Discovery: fire a single contextual hint after each top-level\n // command succeeds. One line, dim, easy to ignore. Disabled with DDT_NO_HINTS=1.\n const ddtAdvisor = new FeatureAdvisor('ddt', DDT_HINT_RULES);\n program.hook('postAction', (_thisCommand, actionCommand) => {\n if (actionCommand.parent !== program) return;\n const tip = ddtAdvisor.advise(actionCommand.name());\n if (tip) {\n console.log(chalk.dim(`\\n ✦ ${tip}`));\n console.log(chalk.dim(' ddt discover · ddt features list'));\n }\n // DSC.6 — explain-features: when the global flag is set, show related\n // features from the catalog for the command that just ran.\n if ((program.opts() as { explainFeatures?: boolean }).explainFeatures) {\n const cmdName = actionCommand.name();\n const related = featuresNs.pickRelatedFeatures(\n featuresNs.DDT_FEATURE_CATALOG,\n cmdName,\n 3,\n 'ddt',\n );\n const hint = featuresNs.renderRelatedFeaturesHint(related, cmdName, 'ddt');\n if (hint) console.log(chalk.dim('\\n' + hint));\n }\n });\n\n await program.parseAsync(process.argv);\n}\n\nmain().catch(async (err: unknown) => {\n console.error(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n // ERR.2 — capture the failure and (with consent) report it; without\n // consent, offer a one-keystroke manual report. Never throws.\n try {\n const reporting = await import('./util/errorReporting.js');\n await reporting.reportCliFailure(err, '0.2.0');\n } catch {\n // Error reporting must never mask the original failure.\n }\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAmBO,SAAS,oBAA6B;AAC3C,QAAM,MAAM,IAAI,yBAAQ,YAAY,EAAE,YAAY,wCAAwC;AAE1F,MACG,QAAQ,YAAY,EACpB,YAAY,iCAAiC,EAC7C,OAAO,iBAAiB,0DAA0D,EAClF,OAAO,mBAAmB,+DAA+D,KAAK,EAC9F;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC,OAAO,oBAAoB,gCAAgC,EAC3D,OAAO,4BAA4B,oCAAoC,EACvE,OAAO,oBAAoB,oBAAoB,E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,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EAGF,EACC;AAAA,IACC;AAAA,IACA;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC,OAAO,aAAa,sEAAsE,IAAI,EAC9F;AAAA,IACC;AAAA,IACA;AAAA,IACA;AAAA,EACF,EACC,OAAO,uBAAuB,6DAA6D,EAC3F;AAAA,IACC;AAAA,IACA;AAAA,IACA;AAAA,EACF,EACC,OAAO,oBAAoB,0DAA0D,EACrF,OAAO,iBAAiB,2CAA2C,KAAK,EACxE;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC,OAAO,wBAAwB,uDAAuD,EACtF;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EAEF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EAEF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EAGF,EACC;AAAA,IACC;AAAA,IACA;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,IACA,kBAAAC,QAAK,KAAK,QAAQ,WAAW;AAAA,EAC/B,EACC;AAAA,IACC;AAAA,IACA;AAAA,IACA,CAA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AM,SAAS,GAAG,EAAE;AAAA,EACvB,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,IACA,CAAC,MAAM,SAAS,GAAG,EAAE;AAAA,EACvB,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,IACA,CAAC,MAAM,SAAS,GAAG,EAAE;AAAA,EACvB,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,IACA,CAAC,MAAM,SAAS,GAAG,EAAE;AAAA,EACvB,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,IACA,CAAC,MAAM,SAAS,GAAG,EAAE;AAAA,EACvB,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,IACA,CAAC,MAAM,SAAS,GAAG,EAAE;AAAA,EACvB,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,IACA,CAAC,MAAM,SAAS,GAAG,EAAE;AAAA,EACvB,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,IACA,CAAC,MAAM,SAAS,GAAG,EAAE;AAAA,EACvB,EACC;AAAA,IACC;AAAA,IACA;AAAA,IACA,CAAC,MAAM,SAAS,GAAG,EAAE;AAAA,EACvB,EACC;AAAA,IACC;AAAA,IACA;AAAA,IACA,CAAC,MAAM,SAAS,GAAG,EAAE;AAAA,EACvB,EACC;AAAA,IACC;AAAA,IACA;AAAA,IACA,CA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KAAK,cAAc,OAAO,cAAc,kBAAkB;AAChE,QAAI,cAAc,WAAW,QAAS;AACtC,UAAM,YAAY,MAAM;AACxB,UAAM,UAAU,qBAAqB,OAAO;AAAA,EAC9C,CAAC;AAID,QAAM,aAAa,IAAI,iCAAe,OAAO,gCAAc;AAC3D,UAAQ,KAAK,cAAc,CAAC,cAAc,kBAAkB;AAC1D,QAAI,cAAc,WAAW,QAAS;AACtC,UAAM,MAAM,WAAW,OAAO,cAAc,KAAK,CAAC;AAClD,QAAI,KAAK;AACP,cAAQ,IAAI,cAAAC,QAAM,IAAI;AAAA,WAAS,GAAG,EAAE,CAAC;AACrC,cAAQ,IAAI,cAAAA,QAAM,IAAI,yCAAsC,CAAC;AAAA,IAC/D;AAGA,QAAK,QAAQ,KAAK,EAAoC,iBAAiB;AACrE,YAAM,UAAU,cAAc,KAAK;AACnC,YAAM,UAAqB;AAAA,QACd;AAAA,QACX;AAAA,QACA;AAAA,QACA;AAAA,MACF;AACA,YAAM,OAAkB,qCAA0B,SAAS,SAAS,KAAK;AACzE,UAAI,KAAM,SAAQ,IAAI,cAAAA,QAAM,IAAI,OAAO,IAAI,CAAC;AAAA,IAC9C;AAAA,EACF,CAAC;AAED,QAAM,QAAQ,WAAW,QAAQ,IAAI;AACvC;AAEA,KAAK,EAAE,MAAM,OAAO,QAAiB;AACnC,UAAQ,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAC9D,UAAQ,WAAW;AAGnB,MAAI;AACF,UAAM,YAAY,MAAM;AACxB,UAAM,UAAU,iBAAiB,KAAK,OAAO;AAAA,EAC/C,QAAQ;AAAA,EAER;AACF,CAAC;","names":["profile","path","fs","import_commander","import_core","path","fs","report","variablesNs","validateNs","import_node_fs","import_node_path","import_commander","import_core","fs","import_node_fs","import_commander","import_core","wrap","pacNs","path","fs","assessment","import_node_fs","import_node_path","import_commander","import_core","import_commander","import_core","path","pacNs","fs","profile","catalog","import_commander","import_node_fs","import_node_path","import_core","parseVariables","pacNs","header","path","fs","import_node_fs","import_node_path","import_commander","import_core","path","fs","import_node_fs","import_node_path","import_commander","import_core","path","fs","profile","objectFilePath","import_node_path","import_node_fs","import_commander","import_core","import_commander","profile","PacSource","import_commander","import_core","fs","path","formatV2","import_node_fs","import_node_path","import_commander","import_core","fs","path","import_node_fs","import_node_path","import_commander","import_core","outPath","path","fs","import_node_fs","import_node_path","import_commander","import_core","import_commander","import_core","fs","profile","import_node_fs","import_commander","import_core","path","fs","profile","import_node_path","import_node_fs","import_commander","import_core","import_core","loadModel","path","fs","import_node_fs","import_node_path","import_commander","import_core","fs","writeFile","path","model","loadModel","focus","direction","fmt","payload","lineage","import_node_fs","import_node_path","import_commander","import_core","loadModel","path","fs","import_node_fs","import_node_path","import_commander","import_core","loadModel","safety","fs","path","import_node_fs","import_node_path","import_commander","import_core","loadModel","emit","path","fs","import_node_fs","import_node_path","import_commander","import_core","fs","path","renderMarkdown","import_node_fs","import_node_path","import_commander","loadModel","path","fs","import_node_fs","import_node_path","import_commander","import_core","catalog","schema","path","fs","import_node_fs","import_node_path","import_commander","loadModel","path","fs","catalog","schema","import_node_fs","import_node_path","import_commander","import_core","path","fs","profile","import_node_fs","import_node_path","import_commander","import_core","catalog","schema","profile","path","fs","import_node_fs","import_node_path","import_commander","import_core","fs","path","loadModel","emit","validateNs","catalog","import_node_fs","import_node_path","import_commander","import_core","loadModel","path","fs","import_node_fs","import_node_path","import_commander","import_core","path","entries","fs","profile","import_node_fs","import_node_path","import_commander","import_core","import_commander","import_core","path","fs","import_node_fs","import_node_path","import_commander","import_commander","import_core","path","fs","profile","import_node_fs","import_node_path","import_commander","import_core","licenseNs","path","import_node_path","import_commander","import_core","path","fs","import_node_fs","import_node_path","import_commander","import_core","licenseNs","path","fs","import_node_fs","import_node_path","import_commander","import_core","loadModel","path","import_node_path","import_commander","import_core","import_commander","import_core","safety","optionsApi","import_commander","import_core","os","path","fs","import_node_fs","import_node_path","import_node_os","import_commander","import_core","license","licenseApi","featuresApi","import_commander","import_core","hostsApi","import_commander","import_core","safetyApi","renderMarkdown","import_commander","import_core","loadModel","renderMarkdown","renderTable","emit","path","fs","import_node_fs","import_node_path","import_commander","import_core","path","import_node_child_process","import_node_fs","import_node_path","import_commander","import_core","path","renderMarkdown","fs","execFileP","canonical","types","import_node_fs","import_node_path","import_node_child_process","import_node_util","import_commander","fs","path","profile","import_node_fs","import_node_path","import_commander","import_core","import_commander","import_core","profile","fs","path","os","totalChanges","execFileP","import_node_child_process","import_node_util","import_node_fs","import_node_os","import_node_path","import_commander","import_core","path","emit","fs","import_node_fs","import_node_path","import_commander","import_core","path","fs","profile","import_commander","import_core","DEFAULT_ROOT","import_node_path","import_commander","import_core","path","fs","path","readStdin","import_node_fs","import_node_path","import_commander","import_core","fs","import_node_fs","import_commander","import_core","readStdin","splitFqn","fs","import_node_fs","import_commander","import_core","readStdin","splitFqn","KINDS","import_commander","import_core","loadModel","renderMarkdown","renderTable","path","fs","import_node_fs","import_node_path","import_commander","import_core","readInput","fs","import_node_fs","import_commander","import_core","readStdin","fs","profile","import_node_fs","import_commander","import_core","import_commander","import_core","profile","import_commander","import_core","chalk","fs","import_commander","import_node_fs","fetchLiveRows","readRowsFile","path","fs","import_fs","import_path","import_commander","import_core","fs","path","core","parseFqn","import_fs","import_path","import_commander","import_core","path","header","fs","import_node_fs","import_node_path","import_commander","import_core","profile","path","fs","import_node_fs","import_node_path","import_commander","import_core","path","header","fs","import_node_fs","import_node_path","import_commander","import_core","chalk","import_node_fs","import_node_path","import_node_os","import_commander","import_chalk","chalk","licenseApi","path","featuresApi","fs","import_node_fs","import_node_path","import_node_os","import_commander","import_core","import_chalk","loadModel","path","fs","import_node_fs","import_node_path","import_commander","import_core","import_commander","import_core","path","import_node_path","import_commander","import_core","verifyCommand","path","fs","import_node_fs","import_node_path","import_commander","import_core","path","fs","import_node_fs","import_node_path","import_commander","import_core","path","fs","import_node_fs","import_node_path","import_commander","collectSqlFiles","fs","path","import_node_path","import_promises","import_commander","import_migrate","fs","path","import_node_path","import_promises","import_commander","import_migrate","fs","path","import_node_fs","import_node_path","import_commander","import_core","fs","path","import_node_fs","import_node_path","import_commander","import_core","path","fs","import_node_fs","import_node_os","import_node_path","import_commander","import_core","os","import_commander","import_core","schema","fs","path","import_node_fs","import_node_path","import_commander","import_core","profile","result","fs","import_commander","import_node_fs","import_core","renderText","fs","path","profile","schema","os","import_commander","import_node_fs","import_node_os","import_node_path","import_core","loadStore","fs","saveStore","path","DEFAULT_STORE","import_commander","import_node_fs","import_node_os","import_node_path","import_core","os","fs","path","DEFAULT_STORE","counter","chalk","weeks","top","import_node_fs","import_node_os","import_node_path","import_commander","import_core","import_chalk","os","import_commander","import_core","import_commander","import_core","errorReport","import_commander","import_discovery","import_chalk","chalk"]}
|