@sdt-tools/cli 0.2.0 → 0.2.6

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.
Files changed (207) hide show
  1. package/dist/advise-tests-6DRSZMBL.js +87 -0
  2. package/dist/advise-tests-6DRSZMBL.js.map +1 -0
  3. package/dist/ai-G4MJWHTM.js +89 -0
  4. package/dist/ai-G4MJWHTM.js.map +1 -0
  5. package/dist/anonymize-QR6JGXA7.js +123 -0
  6. package/dist/anonymize-QR6JGXA7.js.map +1 -0
  7. package/dist/approval-YVHYTV53.js +73 -0
  8. package/dist/approval-YVHYTV53.js.map +1 -0
  9. package/dist/approval-chain-54KKJZS3.js +120 -0
  10. package/dist/approval-chain-54KKJZS3.js.map +1 -0
  11. package/dist/audit-log-QZFH7LUX.js +159 -0
  12. package/dist/audit-log-QZFH7LUX.js.map +1 -0
  13. package/dist/backlog-V2YUIQDL.js +76 -0
  14. package/dist/backlog-V2YUIQDL.js.map +1 -0
  15. package/dist/bisect-GEVYAVL5.js +111 -0
  16. package/dist/bisect-GEVYAVL5.js.map +1 -0
  17. package/dist/bookmarks-57LKS7P6.js +107 -0
  18. package/dist/bookmarks-57LKS7P6.js.map +1 -0
  19. package/dist/branch-W2MGMPSH.js +88 -0
  20. package/dist/branch-W2MGMPSH.js.map +1 -0
  21. package/dist/build-VNIQFKSP.js +23 -0
  22. package/dist/build-VNIQFKSP.js.map +1 -0
  23. package/dist/catalog-JLB5VCEV.js +137 -0
  24. package/dist/catalog-JLB5VCEV.js.map +1 -0
  25. package/dist/changelog-M7XGDYSY.js +220 -0
  26. package/dist/changelog-M7XGDYSY.js.map +1 -0
  27. package/dist/chunk-DGUM43GV.js +11 -0
  28. package/dist/chunk-DGUM43GV.js.map +1 -0
  29. package/dist/chunk-EWXM4KJN.js +25 -0
  30. package/dist/chunk-EWXM4KJN.js.map +1 -0
  31. package/dist/chunk-JP2EZLR5.js +50 -0
  32. package/dist/chunk-JP2EZLR5.js.map +1 -0
  33. package/dist/chunk-VM2H4LAO.js +15 -0
  34. package/dist/chunk-VM2H4LAO.js.map +1 -0
  35. package/dist/chunk-ZWY4ZRHL.js +44 -0
  36. package/dist/chunk-ZWY4ZRHL.js.map +1 -0
  37. package/dist/cli.js +511 -19014
  38. package/dist/cli.js.map +1 -1
  39. package/dist/compare-5O6UTWPJ.js +405 -0
  40. package/dist/compare-5O6UTWPJ.js.map +1 -0
  41. package/dist/compare-profiles-7ZSNIW7B.js +218 -0
  42. package/dist/compare-profiles-7ZSNIW7B.js.map +1 -0
  43. package/dist/completion-I5U5VVAX.js +82 -0
  44. package/dist/completion-I5U5VVAX.js.map +1 -0
  45. package/dist/connection-GNTZDHXF.js +133 -0
  46. package/dist/connection-GNTZDHXF.js.map +1 -0
  47. package/dist/cost-estimate-TJDDH6TO.js +328 -0
  48. package/dist/cost-estimate-TJDDH6TO.js.map +1 -0
  49. package/dist/data-compare-UK2UXAS3.js +134 -0
  50. package/dist/data-compare-UK2UXAS3.js.map +1 -0
  51. package/dist/data-fit-Q45ENBRL.js +125 -0
  52. package/dist/data-fit-Q45ENBRL.js.map +1 -0
  53. package/dist/deploy-status-UUHKVDTI.js +58 -0
  54. package/dist/deploy-status-UUHKVDTI.js.map +1 -0
  55. package/dist/design-PO6UPBL7.js +138 -0
  56. package/dist/design-PO6UPBL7.js.map +1 -0
  57. package/dist/diagnose-6IFMELFR.js +145 -0
  58. package/dist/diagnose-6IFMELFR.js.map +1 -0
  59. package/dist/discover-A7OSZAHK.js +78 -0
  60. package/dist/discover-A7OSZAHK.js.map +1 -0
  61. package/dist/docs-CVRKGUSW.js +177 -0
  62. package/dist/docs-CVRKGUSW.js.map +1 -0
  63. package/dist/drift-XDA3BDYN.js +226 -0
  64. package/dist/drift-XDA3BDYN.js.map +1 -0
  65. package/dist/drift-gate-V7QSIOGZ.js +94 -0
  66. package/dist/drift-gate-V7QSIOGZ.js.map +1 -0
  67. package/dist/error-lookup-7ZWCZJ44.js +56 -0
  68. package/dist/error-lookup-7ZWCZJ44.js.map +1 -0
  69. package/dist/errorReporting-AQXKKGZH.js +109 -0
  70. package/dist/errorReporting-AQXKKGZH.js.map +1 -0
  71. package/dist/exec-PKBHLI7T.js +121 -0
  72. package/dist/exec-PKBHLI7T.js.map +1 -0
  73. package/dist/explain-LWKJOTL7.js +192 -0
  74. package/dist/explain-LWKJOTL7.js.map +1 -0
  75. package/dist/explorer-QOVM6VBD.js +61 -0
  76. package/dist/explorer-QOVM6VBD.js.map +1 -0
  77. package/dist/export-IYYBZ5HE.js +42 -0
  78. package/dist/export-IYYBZ5HE.js.map +1 -0
  79. package/dist/extract-VMMVRQVT.js +102 -0
  80. package/dist/extract-VMMVRQVT.js.map +1 -0
  81. package/dist/features-LE6BDZ2S.js +59 -0
  82. package/dist/features-LE6BDZ2S.js.map +1 -0
  83. package/dist/feedback-M7DM2EQC.js +161 -0
  84. package/dist/feedback-M7DM2EQC.js.map +1 -0
  85. package/dist/find-EME2JG2I.js +176 -0
  86. package/dist/find-EME2JG2I.js.map +1 -0
  87. package/dist/format-TRLWLMGS.js +141 -0
  88. package/dist/format-TRLWLMGS.js.map +1 -0
  89. package/dist/generate-6NAZGZDV.js +152 -0
  90. package/dist/generate-6NAZGZDV.js.map +1 -0
  91. package/dist/graph-QNQDAUO7.js +161 -0
  92. package/dist/graph-QNQDAUO7.js.map +1 -0
  93. package/dist/history-RONA7ZTI.js +199 -0
  94. package/dist/history-RONA7ZTI.js.map +1 -0
  95. package/dist/hosts-YBXY2ZG5.js +49 -0
  96. package/dist/hosts-YBXY2ZG5.js.map +1 -0
  97. package/dist/impact-T2JSANHS.js +59 -0
  98. package/dist/impact-T2JSANHS.js.map +1 -0
  99. package/dist/import-AELYLY6A.js +32 -0
  100. package/dist/import-AELYLY6A.js.map +1 -0
  101. package/dist/import-script-2OF5BI6A.js +83 -0
  102. package/dist/import-script-2OF5BI6A.js.map +1 -0
  103. package/dist/index.cjs +71 -12
  104. package/dist/index.cjs.map +1 -1
  105. package/dist/index.js +95 -31
  106. package/dist/index.js.map +1 -1
  107. package/dist/init-SWRRJMGI.js +57 -0
  108. package/dist/init-SWRRJMGI.js.map +1 -0
  109. package/dist/install-hooks-6SIAGTAF.js +109 -0
  110. package/dist/install-hooks-6SIAGTAF.js.map +1 -0
  111. package/dist/license-OAF22PLZ.js +46 -0
  112. package/dist/license-OAF22PLZ.js.map +1 -0
  113. package/dist/lineage-EW66XJ6O.js +552 -0
  114. package/dist/lineage-EW66XJ6O.js.map +1 -0
  115. package/dist/lint-FQ2OTYTQ.js +143 -0
  116. package/dist/lint-FQ2OTYTQ.js.map +1 -0
  117. package/dist/mcp-SARDMCDV.js +344 -0
  118. package/dist/mcp-SARDMCDV.js.map +1 -0
  119. package/dist/migrate-from-dbt-JVTXPWKQ.js +156 -0
  120. package/dist/migrate-from-dbt-JVTXPWKQ.js.map +1 -0
  121. package/dist/migrate-platform-NTRTOGNR.js +91 -0
  122. package/dist/migrate-platform-NTRTOGNR.js.map +1 -0
  123. package/dist/optimize-CJYWMAWA.js +105 -0
  124. package/dist/optimize-CJYWMAWA.js.map +1 -0
  125. package/dist/perf-LL2CPCJF.js +205 -0
  126. package/dist/perf-LL2CPCJF.js.map +1 -0
  127. package/dist/pii-FBDRDQ2E.js +136 -0
  128. package/dist/pii-FBDRDQ2E.js.map +1 -0
  129. package/dist/pilot-CCQERKPH.js +29 -0
  130. package/dist/pilot-CCQERKPH.js.map +1 -0
  131. package/dist/pr-comment-S5FF4QRX.js +79 -0
  132. package/dist/pr-comment-S5FF4QRX.js.map +1 -0
  133. package/dist/preview-5U4YVCRM.js +47 -0
  134. package/dist/preview-5U4YVCRM.js.map +1 -0
  135. package/dist/profile-7VC57KD2.js +101 -0
  136. package/dist/profile-7VC57KD2.js.map +1 -0
  137. package/dist/promote-AASEFTIA.js +408 -0
  138. package/dist/promote-AASEFTIA.js.map +1 -0
  139. package/dist/publish-UMVIWH6H.js +721 -0
  140. package/dist/publish-UMVIWH6H.js.map +1 -0
  141. package/dist/purge-QMXZKCMD.js +57 -0
  142. package/dist/purge-QMXZKCMD.js.map +1 -0
  143. package/dist/query-log-6OM4GI7W.js +112 -0
  144. package/dist/query-log-6OM4GI7W.js.map +1 -0
  145. package/dist/refactor-LTZQLJ35.js +5799 -0
  146. package/dist/refactor-LTZQLJ35.js.map +1 -0
  147. package/dist/refresh-4TY2AGOU.js +38 -0
  148. package/dist/refresh-4TY2AGOU.js.map +1 -0
  149. package/dist/replay-OOC25FZN.js +117 -0
  150. package/dist/replay-OOC25FZN.js.map +1 -0
  151. package/dist/revert-ODMUVJW6.js +110 -0
  152. package/dist/revert-ODMUVJW6.js.map +1 -0
  153. package/dist/review-XXPWOBFP.js +158 -0
  154. package/dist/review-XXPWOBFP.js.map +1 -0
  155. package/dist/rollback-suggest-6G2HEKFR.js +79 -0
  156. package/dist/rollback-suggest-6G2HEKFR.js.map +1 -0
  157. package/dist/safer-alternative-QFVNLG3L.js +89 -0
  158. package/dist/safer-alternative-QFVNLG3L.js.map +1 -0
  159. package/dist/safety-7QWRSUEZ.js +168 -0
  160. package/dist/safety-7QWRSUEZ.js.map +1 -0
  161. package/dist/savings-RHIXP6IT.js +95 -0
  162. package/dist/savings-RHIXP6IT.js.map +1 -0
  163. package/dist/scan-secrets-5YCQ4UCU.js +54 -0
  164. package/dist/scan-secrets-5YCQ4UCU.js.map +1 -0
  165. package/dist/schema-CIZXCQD2.js +429 -0
  166. package/dist/schema-CIZXCQD2.js.map +1 -0
  167. package/dist/script-K7CIN2P6.js +153 -0
  168. package/dist/script-K7CIN2P6.js.map +1 -0
  169. package/dist/search-BUZ5NXZZ.js +151 -0
  170. package/dist/search-BUZ5NXZZ.js.map +1 -0
  171. package/dist/seed-76QAK276.js +96 -0
  172. package/dist/seed-76QAK276.js.map +1 -0
  173. package/dist/sketch-PTLKDIK3.js +88 -0
  174. package/dist/sketch-PTLKDIK3.js.map +1 -0
  175. package/dist/snapshot-XLPR2OZ5.js +177 -0
  176. package/dist/snapshot-XLPR2OZ5.js.map +1 -0
  177. package/dist/snippets-EK4DK5CN.js +74 -0
  178. package/dist/snippets-EK4DK5CN.js.map +1 -0
  179. package/dist/standards-7T2UY6DD.js +241 -0
  180. package/dist/standards-7T2UY6DD.js.map +1 -0
  181. package/dist/suggest-VGRYSAR6.js +39 -0
  182. package/dist/suggest-VGRYSAR6.js.map +1 -0
  183. package/dist/suggest-constraints-MY5WKUHA.js +160 -0
  184. package/dist/suggest-constraints-MY5WKUHA.js.map +1 -0
  185. package/dist/suite-TRNGZWQM.js +88 -0
  186. package/dist/suite-TRNGZWQM.js.map +1 -0
  187. package/dist/telemetry-3U2QLA2S.js +75 -0
  188. package/dist/telemetry-3U2QLA2S.js.map +1 -0
  189. package/dist/template-ZERIXVXF.js +403 -0
  190. package/dist/template-ZERIXVXF.js.map +1 -0
  191. package/dist/test-5M2ED3WT.js +169 -0
  192. package/dist/test-5M2ED3WT.js.map +1 -0
  193. package/dist/trial-U732FONV.js +31 -0
  194. package/dist/trial-U732FONV.js.map +1 -0
  195. package/dist/validate-T6D2WCOK.js +106 -0
  196. package/dist/validate-T6D2WCOK.js.map +1 -0
  197. package/dist/verify-KXVASEEG.js +76 -0
  198. package/dist/verify-KXVASEEG.js.map +1 -0
  199. package/dist/watch-I6K4BNMA.js +80 -0
  200. package/dist/watch-I6K4BNMA.js.map +1 -0
  201. package/dist/xcompare-TPFLQO6W.js +87 -0
  202. package/dist/xcompare-TPFLQO6W.js.map +1 -0
  203. package/package.json +2 -2
  204. package/dist/cli.cjs +0 -19040
  205. package/dist/cli.cjs.map +0 -1
  206. package/dist/cli.d.cts +0 -1
  207. package/dist/cli.d.ts +0 -1
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/util/logger.ts","../src/commands/init.ts","../src/commands/extract.ts","../src/commands/build.ts","../src/util/help-catalog.ts","../src/util/mapping.ts","../src/commands/publish.ts","../src/util/color.ts","../src/commands/compare.ts","../src/commands/drift.ts","../src/commands/validate.ts","../src/commands/connection.ts","../src/commands/refactor.ts","../src/commands/import.ts","../src/commands/format.ts","../src/commands/completion.ts","../src/commands/telemetry.ts","../src/commands/license.ts","../src/commands/trial.ts","../src/commands/pilot.ts","../src/commands/suite.ts","../src/commands/docs.ts","../src/commands/mcp.ts","../src/commands/ai.ts","../src/commands/explain.ts","../src/commands/feedback.ts","../src/commands/lint.ts","../src/commands/features.ts","../src/commands/hosts.ts","../src/commands/install-hooks.ts","../src/commands/history.ts","../src/commands/audit-log.ts","../src/commands/verify.ts","../src/util/ai-explain.ts","../src/commands/graph.ts","../src/commands/script.ts","../src/commands/revert.ts","../src/commands/snapshot.ts","../src/commands/seed.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/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/commands/xcompare.ts","../src/commands/profile.ts","../src/commands/suggest-constraints.ts","../src/commands/export.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/util/errorReporting.ts","../src/cli.ts"],"sourcesContent":["/**\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","import path from 'node:path';\nimport { promises as fs } from 'node:fs';\nimport { Command } from 'commander';\nimport { newProjectTemplate, saveProject } from '@sdt-tools/core/project';\nimport type { ProjectScope } from '@sdt-tools/core/project';\nimport { logger } from '../util/logger.js';\n\nexport function initCommand(): Command {\n const cmd = new Command('init');\n cmd\n .description('Initialize a new SDT project in the current directory.')\n .option('--name <name>', 'Project name', 'NewSnowflakeProject')\n .option('--scope <scope>', 'Project scope: account | database | schema', 'database')\n .option('--db <database>', 'Database name (required for database/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 (!['account', 'database', 'schema'].includes(scopeType)) {\n throw new Error(`Invalid --scope: ${opts.scope}. Use account | database | schema.`);\n }\n const scope: ProjectScope = { type: scopeType };\n if (scopeType !== 'account') {\n if (!opts.db) throw new Error(`--db is required for scope=${scopeType}`);\n scope.database = String(opts.db);\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}.sdtproj`);\n await saveProject(projectPath, project);\n // Seed conventional folders so the user sees the layout SDT expects.\n const seedFolders = ['databases', 'scripts/pre', 'scripts/post'];\n for (const f of seedFolders) await fs.mkdir(path.join(root, f), { recursive: true });\n logger.success(`Created ${projectPath}`);\n logger.dim(\n ` Scope: ${scopeType}${scope.database ? ' / ' + scope.database : ''}${scope.schema ? ' / ' + scope.schema : ''}`,\n );\n logger.dim(` Next: sdt extract --connection <profile> --output ${root}`);\n });\n return cmd;\n}\n","import path from 'node:path';\nimport { promises as fs } from 'node:fs';\nimport { Command } from 'commander';\nimport { catalog } from '@sdt-tools/core';\nimport { getProfile, SnowflakeConnection } from '@sdt-tools/core/connection';\nimport { AccountExtractor, defaultExtractors } from '@sdt-tools/core/extract';\nimport { writeProjectTree } from '@sdt-tools/core/project';\nimport { logger } from '../util/logger.js';\n\nexport function extractCommand(): Command {\n const cmd = new Command('extract');\n cmd\n .description('Extract a Snowflake account/database/schema into a project layout.')\n .requiredOption('-c, --connection <profile>', 'Connection profile name')\n .requiredOption(\n '-o, --output <path>',\n 'Target project directory (must contain a .sdtproj or pass --init)',\n )\n .option('--db <database>', 'Limit to a single database')\n .option('--schema <schema>', 'Limit to a single schema (requires --db)')\n .option('--types <list>', 'Comma-separated object types to include (default: all implemented)')\n .option(\n '--write-catalog-cache',\n 'Also write the extracted model to the EE1 catalog cache (.sdt/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 Snowflake. Fast / offline — no live connection required. Writes a catalog-snapshot.json to the output dir. Requires a prior `sdt catalog refresh` or `sdt extract --write-catalog-cache` run.',\n false,\n )\n .action(async (opts) => {\n if (opts.useCatalogCache) {\n const out = path.resolve(String(opts.output));\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.databases.length === 0 && snapshot.fingerprint === null) {\n logger.error(\n `No catalog cache found at ${cache.path}. Run \"sdt catalog refresh -c ${String(opts.connection)}\" or \"sdt extract --write-catalog-cache\" first.`,\n );\n process.exitCode = 1;\n return;\n }\n const outPath = path.join(out, '.sdt-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.databases.flatMap((d) =>\n d.schemas.flatMap((s) => s.objects),\n ).length;\n logger.success(\n `Loaded ${objCount} object(s) from catalog cache (${snapshot.databases.length} database(s)) → ${outPath}`,\n );\n logger.dim(\n `Cache was snapshotted at ${snapshot.snapshotAt}. Use \"sdt catalog refresh\" to update it.`,\n );\n return;\n }\n\n const profile = await getProfile(String(opts.connection));\n const conn = new SnowflakeConnection(profile);\n const include = opts.types\n ? new Set(\n String(opts.types)\n .split(',')\n .map((s) => s.trim().toUpperCase()),\n )\n : undefined;\n logger.step(`Connecting to ${profile.account} as ${profile.auth.username}…`);\n await conn.connect();\n try {\n const account = new AccountExtractor(defaultExtractors());\n const objects = await account.extract(\n conn,\n {\n database: opts.db ? String(opts.db) : undefined,\n schema: opts.schema ? String(opts.schema) : undefined,\n },\n { include },\n );\n const out = path.resolve(String(opts.output));\n await fs.mkdir(out, { recursive: true });\n const dumpPath = path.join(out, '.sdt-cache', 'extracted.json');\n await fs.mkdir(path.dirname(dumpPath), { recursive: true });\n await fs.writeFile(dumpPath, JSON.stringify(objects, null, 2));\n const filesCreated = await writeProjectTree(out, objects);\n logger.success(\n `Extracted ${objects.length} object(s) → ${filesCreated} .sql file(s) under ${out} (cache: ${dumpPath}).`,\n );\n\n if (opts.writeCatalogCache) {\n const snapshot = catalog.snapshotFromObjects(objects, {\n connection: String(opts.connection),\n });\n const cache = new catalog.CatalogCache({\n root: out,\n connection: String(opts.connection),\n });\n await cache.set(snapshot);\n logger.success(\n `Wrote catalog cache → ${cache.path} (${snapshot.databases.length} database(s), ${objects.length} object(s)).`,\n );\n }\n } finally {\n await conn.disconnect();\n }\n });\n return cmd;\n}\n","import { Command } from 'commander';\nimport { buildProject } from '@sdt-tools/core/pac';\nimport { logger } from '../util/logger.js';\n\nexport function buildCommand(): Command {\n const cmd = new Command('build');\n cmd\n .description('Build a .sdtpac from a .sdtproj project.')\n .requiredOption('-p, --project <path>', 'Path to the .sdtproj file')\n .option('-o, --out <path>', 'Output .sdtpac path (default: <projectRoot>/bin/<name>.sdtpac)')\n .action(async (opts) => {\n const result = await buildProject(String(opts.project), {\n outputPath: opts.out ? String(opts.out) : undefined,\n });\n logger.success(`Built ${result.outputPath}`);\n logger.dim(` ${result.fileCount} source file(s), ${result.objectCount} object(s) in model`);\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 `sdt explain <name>` for the full entry.\n *\n * Free-tier discoverability: a user who opens `sdt 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 `Databricks/packages/cli/src/util/help-catalog.ts`.\n */\nimport type { Command } from 'commander';\nimport { DEPLOY_OPTIONS_CATALOG, type OptionEntry } from '@sdt-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 `sdt 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 { Option, type Command } from 'commander';\nimport { compare } from '@sdt-tools/core';\n\ntype NameMapping = compare.NameMapping;\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 = compare.mappingFromFile(JSON.parse(raw));\n }\n if (flagMappings.length > 0) {\n const fromArgs = compare.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","import path from 'node:path';\nimport { promises as fs } from 'node:fs';\nimport { Command } from 'commander';\nimport { readPac } from '@sdt-tools/core/pac';\nimport {\n CompareEngine,\n LiveSource,\n buildExecutionPlan,\n defaultSafePlan,\n validatePlan,\n type CompareSource,\n} from '@sdt-tools/core/compare';\nimport {\n ScriptGenerator,\n SnowflakeExecutor,\n buildDeployManifest,\n executePlan,\n resolveDeployScripts,\n formatDeployScript,\n colorizeMigrationScript,\n splitStatements as coreSplitStatements,\n type DeployScript,\n type DeploymentReport,\n type StepResult,\n} from '@sdt-tools/core/deploy';\nimport { compileSlice, mergeDeployOptions, type SdtDeployOptions } from '@sdt-tools/core/project';\nimport {\n ai,\n aiPreflight,\n approval,\n pacFreshness,\n protectedObjects,\n safety,\n license,\n testFramework,\n} from '@sdt-tools/core';\nimport { executeDcmProjectDeploy, mapDcmResultToDeploymentReport } from '@sdt-tools/core/exporters';\nimport { assessDcmCompatibility, formatDcmCompatibilityReport } from '@sdt-tools/core/safety';\nimport { getProfile, SnowflakeConnection } from '@sdt-tools/core/connection';\nimport { logger } from '../util/logger.js';\nimport { attachRelatedOptions } from '../util/help-catalog.js';\nimport { addMappingFlags, buildMappingFromOptions } from '../util/mapping.js';\n\nclass ModelSource implements CompareSource {\n readonly kind = 'pac' as const;\n readonly platform = 'Snowflake' as const;\n readonly label: string;\n private readonly model: Awaited<ReturnType<typeof readPac>>['model'];\n constructor(label: string, model: Awaited<ReturnType<typeof readPac>>['model']) {\n this.label = label;\n this.model = model;\n }\n async load() {\n return this.model;\n }\n}\n\n/**\n * Split a multi-statement SQL block into individual statements. Thin\n * wrapper around `@sdt-tools/core/deploy.splitStatements` so callsites here\n * keep their `string[]` shape.\n */\nfunction splitStatements(sql: string): string[] {\n return coreSplitStatements(sql).map((s) => s.sql);\n}\n\nexport function publishCommand(): Command {\n const cmd = new Command('publish');\n cmd\n .description(\n 'Compare a .sdtpac to a live Snowflake target and apply (or dry-run) the migration.',\n )\n .option(\n '--pac <path>',\n 'Path to a built .sdtpac. Required for a normal publish; omit only with --restore-from-snapshot.',\n )\n .requiredOption('-c, --connection <profile>', 'Connection profile name')\n .option(\n '--restore-from-snapshot <batchId>',\n 'Recovery mode: skip the compare step and emit ALTER TABLE … SWAP WITH 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 `sdt publish --restore-from-snapshot <id>`.\",\n )\n .option(\n '--snapshot-dir <path>',\n 'Snapshot registry directory used with --restore-from-snapshot.',\n '.sdt/snapshots',\n )\n .option('--db <database>', 'Target database (defaults to pac scope.database)')\n .option('--schema <schema>', 'Target schema (defaults to pac scope.schema)')\n .option('--dry-run', 'Print the migration script without executing it', false)\n .option('--apply', 'Execute the migration against the live target (gated by safety)', false)\n .option('--out <path>', 'Write the generated migration script to this path')\n .option(\n '--color <mode>',\n 'Color stdout: auto | always | never. Honors NO_COLOR / SDT_NO_COLOR env vars in auto mode.',\n 'auto',\n )\n .option('--no-pre-scripts', 'Skip pre-deploy scripts even if the pac configures them')\n .option('--no-post-scripts', 'Skip post-deploy scripts even if the pac configures them')\n .option(\n '--no-slice',\n \"Disable the pac's Project Slice (if it has one). Default: the slice baked into the pac is applied automatically and target objects outside the slice are left untouched.\",\n )\n .option('--yes', 'Confirm REQUIRE_YES_FLAG safety gate (required for --apply)', false)\n .option(\n '--confirm-production',\n 'Confirm REQUIRE_CONFIRM_PRODUCTION gate (required for prod-named profiles with destructive changes)',\n false,\n )\n .option(\n '--query-tag <tag>',\n \"Set Snowflake QUERY_TAG for this deploy (audit / observability). The CLI runs ALTER SESSION SET QUERY_TAG='<tag>' before any migration statement so QUERY_HISTORY can attribute the deploy. Defaults to 'sdt:<projectName>@<projectVersion>:<unix-ms>'.\",\n )\n .option(\n '--manifest <path>',\n 'After --apply, write a JSON deploy manifest (every step + status + duration + reverse SQL) to <path>. Replayable via `sdt revert --manifest <path>`.',\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 `sdt 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>:<db>.<schema>).',\n )\n .option(\n '--approvals-root <path>',\n 'Approvals directory (default: .sdt/approvals).',\n path.join('.sdt', 'approvals'),\n )\n .option(\n '--allow-protected <fqns>',\n 'Comma-separated FQNs to allow despite .sdt-protection.json protection. Repeatable.',\n (val: string, prev: string[]) => [...prev, val],\n [] as string[],\n )\n .option(\n '--allow-all-protected',\n 'Override all protection config entries (caution: disables DSR.4 guardrails).',\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 --restore-from-snapshot recipe when tests fail.',\n )\n .option(\n '--via-dcm <stage>',\n 'Enterprise: delegate execution to Snowflake DCM Projects. <stage> is the DCM project FQN (e.g. @MY_DB.PUBLIC.MY_STAGE/my_project). SDT runs its safety pre-flight and DCM compatibility check, then executes EXECUTE DCM PROJECT DEPLOY. DCM must have been populated via `sdt export --dcm` first.',\n )\n .option(\n '--profile <name>',\n 'VARSYNTAX.2 — look up `deploymentProfiles[<name>].variables` from the pac manifest and substitute `$(VAR)` references in the generated migration script. Errors if the named profile is absent from the pac (e.g. pac built before VARSYNTAX.2, or profile not declared in .sdtproj). Distinct from `--connection`, which selects the Snowflake credential profile.',\n )\n .option(\n '--variables <kv>',\n 'VARSYNTAX.2 — comma-separated KEY=VALUE pairs for `$(VAR)` substitution. Merged on top of `--profile <name>` variables (CLI values win on key collision).',\n )\n .action(async (opts) => {\n if (opts.apply && opts.dryRun) {\n logger.error('--apply and --dry-run are mutually exclusive.');\n process.exitCode = 1;\n return;\n }\n\n // Recovery mode — branch out of the normal compare/apply flow and\n // emit ALTER TABLE … SWAP WITH from a recorded snapshot batch.\n if (opts.restoreFromSnapshot) {\n await runRestoreFromSnapshot(opts);\n return;\n }\n\n if (!opts.pac) {\n logger.error('--pac <path> is required (unless --restore-from-snapshot is given).');\n process.exitCode = 1;\n return;\n }\n const pacPath = path.resolve(String(opts.pac));\n const pac = await readPac(pacPath);\n\n // Freshness gate — runs before any network call so stale artifacts\n // are caught fast, before an expensive live-extract round trip.\n const freshnessMode = (opts.freshness as pacFreshness.FreshnessMode | undefined) ?? 'warn';\n if (freshnessMode !== 'skip') {\n const fr = pacFreshness.checkPacFreshness(pac.manifest.builtAt);\n if (fr.status !== 'fresh') {\n const msg = pacFreshness.formatFreshnessWarning(fr, pacPath);\n if (freshnessMode === 'strict') {\n logger.error(msg);\n process.exitCode = 1;\n return;\n } else {\n logger.warn(msg);\n }\n }\n }\n\n const profileName = String(opts.connection);\n const profile = await getProfile(profileName);\n const conn = new SnowflakeConnection(profile);\n const db = opts.db ? String(opts.db) : pac.manifest.scope.database;\n const schema = opts.schema ? String(opts.schema) : pac.manifest.scope.schema;\n const live = new LiveSource(conn, { database: db, schema });\n const source = new ModelSource(pacPath, pac.model);\n\n const baseline: SdtDeployOptions | undefined = pac.manifest.deployOptions;\n const merged = mergeDeployOptions(baseline);\n // Apply the production safety floor: if the profile name looks like\n // production, force preDeployClone=true regardless of what the user\n // authored. Documented in docs/UX_PLAYBOOK.md §\"Per-profile safety\n // floor\". Compose by mutating the `deployment` block in place.\n const isProd = safety.looksLikeProduction(profileName);\n const resolved = {\n ...merged,\n deployment: safety.applyProductionSafetyFloor(merged.deployment, isProd),\n };\n if (isProd && merged.deployment.preDeployClone !== true) {\n logger.info(\n ' Profile \"' +\n profileName +\n '\" looks like production — forcing deployOptions.deployment.preDeployClone=true (safety floor).',\n );\n }\n const preScripts: DeployScript[] =\n opts.preScripts === false\n ? []\n : resolveDeployScripts(pac.source, resolved.deployment.preDeployScriptPatterns);\n const postScripts: DeployScript[] =\n opts.postScripts === false\n ? []\n : resolveDeployScripts(pac.source, resolved.deployment.postDeployScriptPatterns);\n\n // Logical-name mapping (`--map`, `--map-file`) — rewrites pac-side FQNs\n // so a pac built against DB_A can publish into DB_B. See\n // docs/LOGICAL_NAME_MAPPING.md. Mirrors `ddt publish`.\n const nameMapping = await buildMappingFromOptions(opts);\n const engine = new CompareEngine();\n logger.step('Comparing pac to live...');\n\n // Apply the pac's Slice (if any) so target objects outside the slice\n // are partitioned into `outsideScope` rather than treated as removals.\n // --no-slice on the publish command bypasses this.\n const sliceConfig = opts.slice === false ? undefined : pac.manifest.slice;\n const slice = sliceConfig ? compileSlice(sliceConfig) : undefined;\n\n const result = await engine.compare(source, live, {\n ...(nameMapping ? { nameMapping } : {}),\n ...(slice ? { sliceFilter: slice } : {}),\n });\n if (slice) {\n const outside = result.outsideScope?.length ?? 0;\n const refs = result.referenced?.length ?? 0;\n logger.info(\n ' Slice active: ' +\n result.objects.length +\n ' owned · ' +\n outside +\n ' outside scope (untouched) · ' +\n refs +\n ' referenced',\n );\n }\n logger.info(\n ' +' +\n result.summary.added +\n ' -' +\n result.summary.removed +\n ' ~' +\n result.summary.modified +\n ' =' +\n result.summary.unchanged,\n );\n\n // Protection check — refuse to touch protected objects unless overridden.\n const protConfig = await protectedObjects.loadProtectionConfig(path.dirname(pacPath));\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) =>\n s.split(',').map((f) => f.trim()),\n );\n const violations = protectedObjects.checkProtectedObjects(ops, protConfig, {\n allowedFqns,\n allowAll: Boolean(opts.allowAllProtected),\n });\n if (violations.length > 0) {\n logger.error(protectedObjects.formatProtectionViolations(violations));\n process.exitCode = 1;\n await conn.disconnect();\n return;\n }\n }\n\n // VARSYNTAX.2 — resolve `$(VAR)` variables from the pac's\n // deployment-profile snapshot (when `--profile <name>` is given)\n // merged with `--variables KEY=VALUE` (CLI wins on key collision).\n // Absent / empty leaves `$(VAR)` references literal so the prior\n // behavior is preserved when no flag is passed.\n const deploymentProfileName = opts.profile ? String(opts.profile) : undefined;\n let publishVariables: Record<string, string> | undefined;\n if (deploymentProfileName) {\n const profileBlock = pac.manifest.deploymentProfiles?.[deploymentProfileName];\n if (!profileBlock) {\n const available = Object.keys(pac.manifest.deploymentProfiles ?? {});\n logger.error(\n `--profile ${deploymentProfileName}: 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 .sdtproj declare any?).'\n : `Available: ${available.join(', ')}.`),\n );\n process.exitCode = 1;\n await conn.disconnect();\n return;\n }\n if (profileBlock.variables) publishVariables = { ...profileBlock.variables };\n }\n const cliVariables = parsePublishVariables(opts.variables);\n if (cliVariables) {\n publishVariables = { ...(publishVariables ?? {}), ...cliVariables };\n }\n\n const gen = new ScriptGenerator();\n // VARSYNTAX.3 — supply the deploy context so `$(SDT_PROFILE)`,\n // `$(SDT_PROJECT_NAME)`, `$(SDT_PROJECT_VERSION)`, `$(SDT_PLATFORM)`,\n // `$(SDT_TIMESTAMP)`, `$(SDT_USER)` substitute without the operator\n // having to pass them via `--variables`.\n const generateContext: {\n profile?: string;\n projectName?: string;\n projectVersion?: string;\n user?: string;\n } = {\n projectName: pac.manifest.projectName,\n projectVersion: pac.manifest.projectVersion,\n ...(deploymentProfileName ? { profile: deploymentProfileName } : {}),\n ...(profile.auth?.username ? { user: profile.auth.username } : {}),\n };\n const body = gen.generate(result, {\n banner: 'SDT publish: ' + pac.manifest.projectName + ' v' + pac.manifest.projectVersion,\n deployment: resolved.deployment,\n ...(publishVariables ? { variables: publishVariables } : {}),\n context: generateContext,\n });\n\n const sections: string[] = [];\n if (preScripts.length > 0) {\n sections.push('-- ' + '='.repeat(68));\n sections.push('-- PRE-DEPLOY (' + preScripts.length + ' script(s))');\n sections.push('-- ' + '='.repeat(68));\n for (const s of preScripts) sections.push(formatDeployScript(s, 'pre'));\n }\n sections.push(body.sql);\n if (postScripts.length > 0) {\n sections.push('');\n sections.push('-- ' + '='.repeat(68));\n sections.push('-- POST-DEPLOY (' + postScripts.length + ' script(s))');\n sections.push('-- ' + '='.repeat(68));\n for (const s of postScripts) sections.push(formatDeployScript(s, 'post'));\n }\n const fullScript = sections.join('\\n');\n\n logger.info(\n ' pre-deploy: ' +\n preScripts.length +\n ' script(s); post-deploy: ' +\n postScripts.length +\n ' script(s)',\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, fullScript);\n logger.success('Wrote migration script to ' + out);\n }\n\n if (opts.dryRun || !opts.apply) {\n const colorMode = (opts.color as 'auto' | 'always' | 'never' | undefined) ?? 'auto';\n process.stdout.write(colorizeMigrationScript(fullScript, { mode: colorMode }) + '\\n');\n await conn.disconnect();\n return;\n }\n\n // --apply path: run safety classifier and check gates.\n const assessment = safety.assess(result, { deployment: resolved.deployment });\n logger.info(\n ' safety: ' +\n assessment.unrecoverable.length +\n ' unrecoverable, ' +\n assessment.destructive.length +\n ' destructive, ' +\n assessment.expensive.length +\n ' expensive, ' +\n assessment.warnings.length +\n ' warnings',\n );\n if (assessment.blocked) {\n logger.error('Deploy refused: ' + assessment.blockReason);\n await conn.disconnect();\n process.exitCode = 1;\n return;\n }\n\n const satisfied = safety.satisfiedGates({\n yes: Boolean(opts.yes),\n confirmProduction:\n Boolean(opts.confirmProduction) || !safety.looksLikeProduction(profileName),\n allowDropTable: resolved.deployment.allowDropTable,\n allowDropColumn: resolved.deployment.allowDropColumn,\n allowNarrowing: resolved.deployment.allowNarrowingTypes,\n allowTableRebuild: resolved.deployment.allowTableRebuild,\n allowUnrecoverableDrop: resolved.deployment.allowUnrecoverableDrop,\n });\n const outstanding = safety.outstandingGates(assessment, satisfied);\n if (outstanding.length > 0) {\n logger.error(\n 'Outstanding safety gate(s): ' +\n outstanding.join(', ') +\n '. Pass --yes / --confirm-production or set the matching deployOptions.deployment.* flag in the profile.',\n );\n await conn.disconnect();\n process.exitCode = 1;\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 ?? `${profileName}:${db}.${schema}`);\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 logger.error(\n 'Approval gate blocked deploy: ' +\n (outcome.blockReason ?? 'gate not satisfied') +\n `. Record approvals with \\`sdt approval add ${deployId} --as <user>\\`.`,\n );\n await conn.disconnect();\n process.exitCode = 1;\n return;\n }\n logger.info(\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 logger.error(\n '--ai-preflight needs a narrative. Provide it inline via --ai-preflight-text or via stdin.',\n );\n await conn.disconnect();\n process.exitCode = 1;\n return;\n }\n logger.step('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: fullScript,\n target: `${db}.${schema}@${profileName}`,\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 logger.info(' preflight verdict: ' + verdict.verdict);\n if (verdict.reasoning) logger.info(' preflight reasoning: ' + verdict.reasoning);\n for (const d of verdict.discrepancies) logger.info(' • ' + d);\n\n const isBlocking =\n verdict.verdict === 'mismatch' ||\n (opts.strictAiPreflight && verdict.verdict === 'partial');\n if (isBlocking && !opts.confirmAfterPreflightMismatch) {\n logger.error(\n `Deploy refused: AI preflight returned \"${verdict.verdict}\". Re-run with --confirm-after-preflight-mismatch to override, or revise the narrative.`,\n );\n await conn.disconnect();\n process.exitCode = 1;\n return;\n }\n if (verdict.parseFailed) {\n logger.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 logger.error(\n `--ai-preflight failed: ${msg}. Configure an AI provider via \\`sdt ai status\\` or omit --ai-preflight.`,\n );\n await conn.disconnect();\n process.exitCode = 1;\n return;\n }\n }\n\n // ── DCM path — replaces the standard executor when --via-dcm is set ──\n if (opts.viaDcm) {\n const dcmStage = String(opts.viaDcm);\n\n // Enterprise license check (warn mode for v0.1 — feature is allowed with warning if no license).\n const lic = await license.loadLicense();\n const licCheck = license.checkProFeature(lic, 'dcm-deploy');\n if (licCheck.warning) logger.warn('[Enterprise] ' + licCheck.warning);\n\n // DCM compatibility pre-flight — always runs, even for --dry-run.\n const dcmCompatReport = assessDcmCompatibility(result);\n if (dcmCompatReport.blocked) {\n logger.error('--via-dcm blocked:\\n' + formatDcmCompatibilityReport(dcmCompatReport));\n await conn.disconnect();\n process.exitCode = 1;\n return;\n }\n if (dcmCompatReport.findings.length > 0) {\n logger.warn(\n 'DCM compatibility warnings:\\n' + formatDcmCompatibilityReport(dcmCompatReport),\n );\n }\n\n if (opts.dryRun || !opts.apply) {\n logger.info(\n 'DCM compatibility check passed (' +\n dcmCompatReport.findings.length +\n ' warning(s)). Use --apply to execute via DCM.',\n );\n await conn.disconnect();\n return;\n }\n\n // Execute via DCM.\n logger.step('Executing via DCM: EXECUTE DCM PROJECT ' + dcmStage + ' DEPLOY');\n const dcmResult = await executeDcmProjectDeploy(conn, dcmStage);\n const bodyReport = mapDcmResultToDeploymentReport(dcmResult);\n\n if (dcmResult.overallStatus === 'SUCCESS') {\n logger.success(\n 'DCM deploy complete. ' + dcmResult.objects.length + ' object(s) processed.',\n );\n } else {\n logger.error(\n 'DCM deploy finished with failures: ' +\n dcmResult.failures.length +\n ' failed, ' +\n dcmResult.objects.length +\n ' total.',\n );\n process.exitCode = 1;\n }\n\n if (opts.manifest) {\n const m = buildDeployManifest(bodyReport, profile.account);\n const mPath = path.resolve(String(opts.manifest));\n await fs.mkdir(path.dirname(mPath), { recursive: true });\n await fs.writeFile(mPath, JSON.stringify(m, null, 2) + '\\n', 'utf8');\n logger.success('Wrote deploy manifest → ' + mPath);\n }\n\n await conn.disconnect();\n return;\n }\n // ── End DCM path ────────────────────────────────────────────────────────\n\n // Set the Snowflake QUERY_TAG before executing any migration\n // statement. Threading the tag into QUERY_HISTORY is what makes a\n // deploy auditable after the fact (\"which statements ran as part of\n // sdt-vX.Y.Z published at 13:42?\"). Default tag encodes the project\n // identity + a millisecond timestamp so two back-to-back applies are\n // distinguishable.\n const queryTag =\n typeof opts.queryTag === 'string' && opts.queryTag.length > 0\n ? String(opts.queryTag)\n : `sdt:${pac.manifest.projectName}@${pac.manifest.projectVersion}:${Date.now()}`;\n try {\n await conn.query(`ALTER SESSION SET QUERY_TAG = '${queryTag.replace(/'/g, \"''\")}'`);\n logger.info(' query_tag: ' + queryTag);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n logger.error(\n 'Failed to set QUERY_TAG: ' +\n msg +\n '. Continuing without tag — audit attribution will be missing.',\n );\n }\n\n // Execute. Statements run sequentially. Snowflake DDL auto-commits per\n // statement, so partial deploys do not roll back automatically; if\n // preDeployClone was enabled, use UNDROP DATABASE or clone-swap to\n // recover. The main body runs through executePlan + SnowflakeExecutor\n // so every step's reverseSql is captured for `sdt revert`. Pre/post\n // scripts are file-based (no emitter, no reverseSql) so they keep the\n // simpler sequential-query path.\n logger.step('Applying migration...');\n let executed = 0;\n let failed = 0;\n const runOne = async (sql: string, label: string): Promise<boolean> => {\n const stmts = splitStatements(sql);\n for (const stmt of stmts) {\n try {\n await conn.query(stmt);\n executed += 1;\n } catch (err) {\n failed += 1;\n const msg = err instanceof Error ? err.message : String(err);\n logger.error(' [' + label + '] failed: ' + msg + '\\n ' + stmt);\n return false;\n }\n }\n return true;\n };\n\n let ok = true;\n for (const s of preScripts) {\n logger.info(' pre: ' + s.path);\n ok = await runOne(s.sql, 'pre/' + s.path);\n if (!ok) break;\n }\n\n let bodyReport: DeploymentReport | undefined;\n if (ok) {\n const plan = defaultSafePlan(result);\n const validated = validatePlan(result, plan);\n const steps = buildExecutionPlan(result, validated, {\n deployment: resolved.deployment,\n });\n if (steps.length > 0) {\n const executor = new SnowflakeExecutor(conn, {\n onStatement: (sql) => {\n executed += 1;\n const head = sql.split('\\n')[0]?.slice(0, 100) ?? '';\n logger.info(' → ' + head + (sql.length > 100 ? ' …' : ''));\n },\n });\n bodyReport = await executePlan(steps, executor, {\n rollbackOnFailure: false,\n onStepEnd: (r: StepResult) => {\n if (r.status === 'FAILED') {\n failed += 1;\n logger.error(\n ' [' +\n r.step.fqn +\n '] failed: ' +\n (r.error ?? 'unknown') +\n '\\n ' +\n r.step.forwardSql,\n );\n }\n },\n });\n if (bodyReport.finalState !== 'CLEAN_SUCCESS') ok = false;\n }\n }\n\n if (ok) {\n for (const s of postScripts) {\n logger.info(' post: ' + s.path);\n ok = await runOne(s.sql, 'post/' + s.path);\n if (!ok) break;\n }\n }\n\n // Write deploy manifest if requested. The manifest captures every\n // body step (forwardSql + reverseSql + status + duration) and is\n // replayable via `sdt revert --manifest <path>`. Pre/post scripts are\n // not in the manifest (they have no inverse).\n if (opts.manifest && bodyReport) {\n const m = buildDeployManifest(bodyReport, profile.account);\n const mPath = path.resolve(String(opts.manifest));\n await fs.mkdir(path.dirname(mPath), { recursive: true });\n await fs.writeFile(mPath, JSON.stringify(m, null, 2) + '\\n', 'utf8');\n logger.success('Wrote deploy manifest → ' + mPath);\n }\n\n if (ok) {\n logger.success('Deploy complete. ' + executed + ' statement(s) executed.');\n\n // Post-deploy DQ tests (DQ.6).\n if (opts.postDeployTests) {\n const projectRoot = path.resolve(String(opts.postDeployTests));\n logger.step('Running post-deploy DQ tests from ' + projectRoot + '...');\n const testFiles = await testFramework.discoverTests(projectRoot);\n if (testFiles.length === 0) {\n logger.warn(\n ' POST_DEPLOY_DQ: no tests found under ' + projectRoot + '/tests/ — skipping.',\n );\n } else {\n const report = await testFramework.runTestFiles(testFiles, conn);\n process.stdout.write(testFramework.renderTextReport(report));\n if (report.summary.blocking) {\n logger.error(\n 'POST_DEPLOY_DQ_FAILED: ' +\n report.summary.fail +\n ' fail / ' +\n report.summary.error +\n ' error.' +\n (opts.manifest\n ? ' Recover: `sdt revert --manifest ' + String(opts.manifest) + '`'\n : ' Consider re-deploying prior version or using `sdt revert --manifest` if --manifest was used.'),\n );\n process.exitCode = 2;\n } else {\n logger.success(\n ' POST_DEPLOY_DQ: ' + report.summary.pass + '/' + report.summary.total + ' pass.',\n );\n }\n }\n }\n } else {\n logger.error(\n 'Deploy aborted after ' +\n executed +\n ' statement(s); ' +\n failed +\n ' failure(s). Recover via UNDROP / clone-swap if preDeployClone was set.',\n );\n process.exitCode = 1;\n }\n await conn.disconnect();\n });\n addMappingFlags(cmd);\n attachRelatedOptions(cmd, [\n 'deployment.allowDropTable',\n 'deployment.allowDropColumn',\n 'deployment.allowUnrecoverableDrop',\n 'deployment.allowNarrowingTypes',\n 'deployment.preDeployClone',\n 'deployment.blockOnPossibleDataLoss',\n 'deployment.preserveTargetOnlyObjects',\n ]);\n return cmd;\n}\n\n/**\n * `sdt publish --restore-from-snapshot <batchId>` recovery path.\n *\n * Loads the batch from the registry, emits the restore SQL (one\n * `ALTER TABLE … SWAP WITH` per source object, or a MANUAL hint row for\n * materialised objects), and either prints it (dry-run / no --apply) or\n * executes it against the live target (--apply --yes, --confirm-production\n * for prod-named profiles).\n *\n * Skips: pac freshness, compare, safety classifier, AI preflight, approval\n * gate, DCM path, 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 ?? '.sdt/snapshots'));\n const profileName = String(opts.connection);\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 logger.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 logger.info(`Restoring from batch ${batch.batchId} (createdAt=${batch.createdAt})`);\n logger.info(\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 logger.success(`Wrote restore SQL → ${out}`);\n }\n\n if (opts.dryRun || !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 logger.error('--apply requires --yes (restore replaces production tables via SWAP WITH).');\n process.exitCode = 1;\n return;\n }\n if (safety.looksLikeProduction(profileName) && !opts.confirmProduction) {\n logger.error(\n `Profile \"${profileName}\" looks like production — also pass --confirm-production to restore.`,\n );\n process.exitCode = 1;\n return;\n }\n\n const profile = await getProfile(profileName);\n const conn = new SnowflakeConnection(profile);\n let executed = 0;\n let failed = 0;\n try {\n for (const stmt of coreSplitStatements(sql).map((s) => s.sql)) {\n try {\n await conn.query(stmt);\n executed += 1;\n const head = stmt.split('\\n')[0]?.slice(0, 100) ?? '';\n logger.info(' → ' + head + (stmt.length > 100 ? ' …' : ''));\n } catch (err) {\n failed += 1;\n const msg = err instanceof Error ? err.message : String(err);\n logger.error(` [restore ${batch.batchId}] ${msg}\\n ${stmt}`);\n }\n }\n } finally {\n await conn.disconnect();\n }\n\n if (failed === 0) {\n logger.success(`Restore complete. ${executed} statement(s) executed.`);\n } else {\n logger.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\n/**\n * VARSYNTAX.2 — parse the `--variables KEY=VALUE,KEY=VALUE,...` flag.\n * Returns undefined when nothing is parsed (no KV pairs, missing values,\n * empty string) so callers can `...(parsed ? { variables: parsed } : {})`\n * without leaking an empty object.\n */\nexport function parsePublishVariables(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 * ANSI severity coloring for CLI output. Resolves the `--color` flag\n * against the current TTY state and returns a `colorize` function\n * that wraps text in the right ANSI code (or returns it unchanged\n * when color is disabled).\n *\n * Conventions used across SDT/DDT CLI surfaces:\n * - UNRECOVERABLE → bold red\n * - DESTRUCTIVE → red\n * - EXPENSIVE → yellow\n * - WARNING → cyan\n * - SAFE / OK → green\n *\n * Paired with `Databricks/packages/cli/src/util/color.ts`.\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 // auto — only color when stdout is a TTY AND NO_COLOR env isn't set.\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 /** Apply ANSI coloring to a multi-line block based on per-line severity tokens (🛑, ⚠, ✓, etc). */\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 // Walk each line; apply the strongest matching severity color.\n // The marker tokens (🛑/⚠/✓/info-prefixes) are stable across\n // `safety.formatReversibilityBuckets` and the diagnostics output.\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 path from 'node:path';\nimport { promises as fs } from 'node:fs';\nimport { Command } from 'commander';\nimport {\n CompareEngine,\n LiveSource,\n PacSource,\n ProjectSource,\n writeCompareHistory,\n type CompareSource,\n} from '@sdt-tools/core/compare';\nimport { getProfile, SnowflakeConnection } from '@sdt-tools/core/connection';\nimport { compileSlice, loadProject } from '@sdt-tools/core/project';\nimport { ai, safety, typecheck } from '@sdt-tools/core';\nimport { logger } from '../util/logger.js';\nimport { attachRelatedOptions } from '../util/help-catalog.js';\nimport { makeColorizer, resolveColorMode } from '../util/color.js';\nimport { addMappingFlags, buildMappingFromOptions } from '../util/mapping.js';\n\n/**\n * Auto-load a slice from a `.sdtproj` argument. Returns `undefined` when\n * the argument is not a `.sdtproj` or the project doesn't declare a slice.\n * Suite-level invocations bypass this and pass a slice directly.\n */\nasync function maybeLoadSliceFromArg(\n arg: string,\n): Promise<ReturnType<typeof compileSlice> | undefined> {\n if (!arg.toLowerCase().endsWith('.sdtproj')) return undefined;\n const loaded = await loadProject(arg);\n if (!loaded.project.slice) return undefined;\n return compileSlice(loaded.project.slice);\n}\n\n/**\n * Resolve a polymorphic source/target argument. Supported forms:\n * - path/to/foo.sdtproj\n * - path/to/foo.sdtpac\n * - snowflake://<profile>[/db[/schema]]\n */\nasync function resolveSource(arg: string): Promise<CompareSource> {\n if (arg.startsWith('snowflake://')) {\n const rest = arg.slice('snowflake://'.length);\n const [profileName, db, schema] = rest.split('/');\n if (!profileName) throw new Error(`Invalid snowflake URI: ${arg}`);\n const profile = await getProfile(profileName);\n const conn = new SnowflakeConnection(profile);\n return new LiveSource(conn, { database: db, schema });\n }\n const lower = arg.toLowerCase();\n if (lower.endsWith('.sdtproj')) return new ProjectSource(arg);\n if (lower.endsWith('.sdtpac')) return new PacSource(arg);\n throw new Error(\n `Unrecognized source: ${arg}. Use *.sdtproj, *.sdtpac, or snowflake://<profile>[/db[/schema]].`,\n );\n}\n\nexport function compareCommand(): Command {\n const cmd = new Command('compare');\n cmd\n .description(\n 'Compare two schemas. Sources may be .sdtproj, .sdtpac, or snowflake://<profile>[/db[/schema]].',\n )\n .argument('<source>', 'Left side of the comparison')\n .argument('<target>', 'Right side of the comparison')\n .option('-o, --output <path>', 'Write JSON result to this path')\n .option('--format <format>', 'Output format: json | summary | markdown', 'summary')\n .option('--ignore-case', 'Treat unquoted identifiers case-insensitively', false)\n .option(\n '--no-slice',\n \"Disable the source project's Slice (if it has one). Default: a project's slice is applied 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 `sdt 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: `.sdt/impact.json` resolved relative to the source `.sdtproj` directory (or CWD if the source is not a project). 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 `.sdt/history/compare/`, exportable via `sdt audit-log emit`.',\n )\n .action(async (sourceArg, targetArg, opts) => {\n // Logical-name mapping (`--map`, `--map-file`) — rewrites source-side\n // FQNs so two schemas whose database / schema names differ can compare\n // semantically. See docs/LOGICAL_NAME_MAPPING.md. Mirrors `ddt compare`.\n const nameMapping = await buildMappingFromOptions(opts);\n const source = await resolveSource(String(sourceArg));\n const target = await resolveSource(String(targetArg));\n\n // Auto-load slice from the source `.sdtproj` unless --no-slice was set.\n // The target side (live or pac) doesn't carry a slice; it's the\n // project's slice that defines the scope.\n const slice =\n opts.slice === false ? undefined : await maybeLoadSliceFromArg(String(sourceArg));\n\n const engine = new CompareEngine();\n const startedAt = new Date().toISOString();\n const result = await engine.compare(source, target, {\n ignoreCase: Boolean(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(compareHistoryRoot(String(sourceArg)), {\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.output) {\n const out = path.resolve(String(opts.output));\n await fs.mkdir(path.dirname(out), { recursive: true });\n await fs.writeFile(out, JSON.stringify(result, null, 2));\n logger.success(`Wrote ${out}`);\n }\n\n if (opts.format === 'json') {\n process.stdout.write(JSON.stringify(result, null, 2) + '\\n');\n return;\n }\n if (opts.format === 'markdown') {\n const assessment = safety.assess(result);\n process.stdout.write(renderCompareMarkdown(result, assessment) + '\\n');\n return;\n }\n logger.info(\n `Compare ${result.source.kind}:${result.source.label} → ${result.target.kind}:${result.target.label}`,\n );\n if (slice) {\n const outside = result.outsideScope?.length ?? 0;\n const refs = result.referenced?.length ?? 0;\n logger.info(\n ` Slice active: ${result.objects.length} owned · ${outside} outside scope (untouched) · ${refs} referenced`,\n );\n }\n logger.info(\n ` +${result.summary.added} added, -${result.summary.removed} removed, ~${result.summary.modified} modified, =${result.summary.unchanged} unchanged`,\n );\n for (const o of result.objects) {\n if (o.kind === 'unchanged') continue;\n logger.info(` ${o.kind.padEnd(8)} ${o.identity.objectType.padEnd(20)} ${o.identity.fqn}`);\n }\n\n // Reversibility-grouped safety findings. Three buckets — Unrecoverable\n // first (highest urgency), then Data-impacting, then Reversible.\n // Empty diff is silent; assessment.blocked is surfaced once findings\n // exist.\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 logger.info('');\n logger.info('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')) logger.info(' ' + line);\n if (assessment.blocked && assessment.blockReason) {\n logger.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. Output is the assistant's plain-English narration.\n if (opts.explain) {\n logger.info('');\n logger.info('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')) logger.info(' ' + line);\n } catch (err) {\n logger.error(' --explain failed: ' + (err instanceof Error ? err.message : String(err)));\n logger.error(\n ' Run `sdt ai status` to verify your AI provider is configured (`sdt 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 String(sourceArg),\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 logger.info('');\n logger.info(\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 logger.info(\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 logger.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 logger.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 logger.info('Type-safety gate PASSED — no breaking-change ripples detected.');\n }\n }\n });\n addMappingFlags(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\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 * `<project-dir>/.sdt/impact.json` when the source is a `.sdtproj`,\n * otherwise `<cwd>/.sdt/impact.json`.\n */\nasync function writeImpactJson(\n result: Parameters<typeof typecheck.analyzeImpact>[0],\n explicitPath: string | undefined,\n sourceArg: string,\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) : defaultImpactPath(sourceArg);\n await fs.mkdir(path.dirname(outPath), { recursive: true });\n await fs.writeFile(outPath, typecheck.serializeImpactFile(file));\n logger.success(\n `Wrote ${outPath} — ${summary.findingsCount} finding(s), ${summary.errors} error / ${summary.warnings} warning ripple(s).`,\n );\n}\n\nfunction defaultImpactPath(sourceArg: string): string {\n if (sourceArg.toLowerCase().endsWith('.sdtproj')) {\n return path.resolve(path.dirname(sourceArg), '.sdt', 'impact.json');\n }\n return path.resolve('.sdt', 'impact.json');\n}\n\n/**\n * AUDITCMP.1 — workspace root for the compare-history record. Project /\n * pac sources anchor the audit trail next to the artifact being compared;\n * live (snowflake://) sources fall back to CWD.\n */\nfunction compareHistoryRoot(sourceArg: string): string {\n const lower = sourceArg.toLowerCase();\n if (lower.endsWith('.sdtproj') || lower.endsWith('.sdtpac')) {\n return path.dirname(path.resolve(sourceArg));\n }\n return process.cwd();\n}\n\nexport const SYSTEM_PROMPT = `You are a senior Snowflake 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\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\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","import { Command } from 'commander';\nimport path from 'node:path';\nimport { readPac } from '@sdt-tools/core/pac';\nimport {\n CompareEngine,\n DbtManifestSource,\n LiveSource,\n type CompareSource,\n} from '@sdt-tools/core/compare';\nimport { getProfile, SnowflakeConnection } from '@sdt-tools/core/connection';\nimport { loadProject } from '@sdt-tools/core/project';\nimport { driftAnomaly } from '@sdt-tools/core';\nimport { logger } from '../util/logger.js';\nimport { addMappingFlags, buildMappingFromOptions } from '../util/mapping.js';\nimport { attachRelatedOptions } from '../util/help-catalog.js';\n\nclass ModelSource implements CompareSource {\n readonly kind = 'pac' as const;\n readonly platform = 'Snowflake' as const;\n readonly label: string;\n private readonly model: Awaited<ReturnType<typeof readPac>>['model'];\n constructor(label: string, model: Awaited<ReturnType<typeof readPac>>['model']) {\n this.label = label;\n this.model = model;\n }\n async load() {\n return this.model;\n }\n}\n\nfunction driftWatchSubcommand(): Command {\n const sub = new Command('watch');\n sub\n .description(\n 'Poll a project against the live Snowflake account on a fixed interval. Prints DRIFT_DETECTED events to stdout (or POSTs to --webhook) when the catalog diverges from the project pac.',\n )\n .requiredOption('-p, --project <path>', 'Path to .sdtproj')\n .requiredOption('-c, --connection <profile>', 'Connection profile name')\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\n const profile = await getProfile(String(opts.connection));\n const conn = new SnowflakeConnection(profile);\n const loaded = await loadProject(String(opts.project));\n const pacPath = path.join(loaded.rootDir, 'bin', `${loaded.project.name}.sdtpac`);\n const scope = {\n database: loaded.project.scope.database,\n schema: loaded.project.scope.schema,\n };\n\n if (!quiet && format === 'text') {\n logger.info(\n `drift watch: polling every ${intervalSecs}s — ${loaded.project.name} → ${profile.account}`,\n );\n logger.info('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') logger.warn(`Webhook POST failed: HTTP ${res.status}`);\n } catch (err) {\n if (format === 'text')\n logger.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 pac = await readPac(pacPath);\n const declared = new ModelSource(pacPath, pac.model);\n const live = new LiveSource(conn, scope);\n const engine = new CompareEngine();\n const result = await engine.compare(declared, 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 project: loaded.project.name,\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 logger.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, project: loaded.project.name }) +\n '\\n',\n );\n else logger.info(`[${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 logger.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\nexport function driftCommand(): Command {\n const cmd = new Command('drift');\n cmd\n .description(\n 'Check whether a live Snowflake target has drifted from the project pac or a dbt manifest.',\n )\n .option('-p, --project <path>', 'Path to .sdtproj (required unless --vs-dbt-project is used)')\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, --project is not required.',\n )\n .requiredOption('-c, --connection <profile>', 'Connection profile name')\n .option(\n '--anomalies',\n 'Also classify drift via the anomaly detector (new grants to PUBLIC, bypass-role grants, owner changes, audit-column drops, mask removals, new bypass-named roles).',\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 // Logical-name mapping (`--map`, `--map-file`) — rewrites declared-side\n // FQNs so a project authored against DEV names can be drift-checked\n // against a PROD target. See docs/LOGICAL_NAME_MAPPING.md. Mirrors\n // `ddt drift` (RH3.2 parity).\n addMappingFlags(cmd);\n cmd.action(async (opts) => {\n if (!opts.project && !opts.vsDBtProject) {\n logger.error('Provide either --project <path> or --vs-dbt-project <path>.');\n process.exitCode = 1;\n return;\n }\n\n const nameMapping = await buildMappingFromOptions(opts);\n const profile = await getProfile(String(opts.connection));\n const conn = new SnowflakeConnection(profile);\n\n let declared: CompareSource;\n let scope: { database?: string; schema?: string };\n\n if (opts.vsDBtProject) {\n declared = new DbtManifestSource(String(opts.vsDBtProject), `dbt:${opts.vsDBtProject}`);\n scope = {};\n } else {\n const loaded = await loadProject(String(opts.project));\n const pacPath = path.join(loaded.rootDir, 'bin', `${loaded.project.name}.sdtpac`);\n const pac = await readPac(pacPath);\n declared = new ModelSource(pacPath, pac.model);\n scope = {\n database: loaded.project.scope.database,\n schema: loaded.project.scope.schema,\n };\n }\n\n const live = new LiveSource(conn, scope);\n const engine = new CompareEngine();\n const result = await engine.compare(declared, live, {\n ...(nameMapping ? { nameMapping } : {}),\n });\n const drifted = result.summary.added + result.summary.removed + result.summary.modified;\n if (!opts.anomaliesOnly) {\n if (drifted === 0) {\n logger.success('No drift detected.');\n } else {\n logger.warn(\n `Drift: +${result.summary.added} -${result.summary.removed} ~${result.summary.modified}`,\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 logger.info('Anomaly scan: 0 findings.');\n } else {\n logger.warn(`Anomaly scan: ${report.totalAnomalies} finding(s):`);\n for (const a of report.anomalies) {\n logger.info(` [${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(failOn as driftAnomaly.AnomalySeverity);\n const triggered = report.anomalies.some(\n (a) => driftAnomaly.anomalySeverityRank(a.severity) <= failRank,\n );\n if (triggered) process.exitCode = 1;\n }\n }\n }\n await conn.disconnect();\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 { project, validate as validateNs, variables as variablesNs } from '@sdt-tools/core';\nimport { logger } from '../util/logger.js';\nimport { attachRelatedOptions } from '../util/help-catalog.js';\n\n/**\n * `sdt validate` — schema-shape sanity check on a `.sdtproj`. Default\n * mode confirms the project file parses, scope resolves, and object\n * files discover successfully. The `--references` flag adds the\n * Microsoft-SSDT-style build-time semantic resolution: every object reference in every\n * project body is classified as resolved / dangling / external /\n * temporary / dynamic, with warnings for unresolved references.\n *\n * Column-level resolution is Phase 2 (BACKLOG-tracked).\n */\nexport function validateCommand(): Command {\n const cmd = new Command('validate');\n cmd\n .description(\n 'Validate a .sdtproj — schema check; optionally resolve every object reference (--references).',\n )\n .requiredOption('-p, --project <path>', 'Path to .sdtproj')\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 project.loadProject(String(opts.project));\n const files = await project.discoverObjectFiles(loaded);\n logger.success(`Project ${loaded.project.name} v${loaded.project.version} is valid.`);\n logger.dim(\n ` Scope: ${loaded.project.scope.type}${loaded.project.scope.database ? '/' + loaded.project.scope.database : ''}`,\n );\n logger.dim(` Files: ${files.length}`);\n logger.dim(` 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 logger.dim(` Variables: ${report.references.length} reference(s), all declared.`);\n }\n\n if (!opts.references) return;\n\n logger.dim('');\n logger.dim('Resolving references…');\n const model = await project.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 logger.dim(`Wrote ${out} (${payload.length} bytes, ${report.findings.length} finding(s)).`);\n } else {\n process.stdout.write(payload + (payload.endsWith('\\n') ? '' : '\\n'));\n }\n\n // Non-zero exit when at least one ERROR-severity finding fires so\n // `sdt validate --references` can gate a CI step.\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 { Command } from 'commander';\nimport {\n getProfile,\n loadProfiles,\n removeProfile,\n SnowflakeConnection,\n upsertProfile,\n type ConnectionProfile,\n} from '@sdt-tools/core/connection';\nimport { logger } from '../util/logger.js';\n\nexport function connectionCommand(): Command {\n const cmd = new Command('connection');\n cmd.description('Manage Snowflake connection profiles.');\n\n cmd\n .command('list')\n .description('List configured connection profiles.')\n .action(async () => {\n const profiles = await loadProfiles();\n if (!profiles.length) {\n logger.dim('(no profiles configured — run `sdt connection add` to add one)');\n return;\n }\n for (const p of profiles) {\n logger.info(\n ` ${p.name.padEnd(20)} ${p.account.padEnd(28)} ${p.auth.method} as ${p.auth.username}`,\n );\n }\n });\n\n cmd\n .command('add')\n .description('Add or replace a connection profile.')\n .requiredOption('--name <name>', 'Profile name')\n .requiredOption('--account <account>', 'Snowflake account locator (e.g. xy12345.us-east-1)')\n .requiredOption('--user <user>', 'Snowflake username')\n .option(\n '--auth <method>',\n 'Auth method: PASSWORD | KEY_PAIR | OAUTH | EXTERNAL_BROWSER | MFA',\n 'PASSWORD',\n )\n .option('--password <value>', 'Password or env:VAR_NAME placeholder')\n .option('--key <path>', 'Path to RSA private key (for KEY_PAIR auth)')\n .option('--key-passphrase <value>', 'Passphrase or env:VAR_NAME placeholder')\n .option('--role <role>', 'Default role')\n .option('--warehouse <wh>', 'Default warehouse')\n .option('--database <db>', 'Default database')\n .option('--schema <schema>', 'Default schema')\n .action(async (opts) => {\n const auth = String(opts.auth).toUpperCase() as ConnectionProfile['auth']['method'];\n let authBlock: ConnectionProfile['auth'];\n switch (auth) {\n case 'PASSWORD':\n if (!opts.password) throw new Error('--password is required for PASSWORD auth');\n authBlock = {\n method: 'PASSWORD',\n username: String(opts.user),\n password: String(opts.password),\n };\n break;\n case 'KEY_PAIR':\n if (!opts.key) throw new Error('--key is required for KEY_PAIR auth');\n authBlock = {\n method: 'KEY_PAIR',\n username: String(opts.user),\n privateKeyPath: String(opts.key),\n privateKeyPassphrase: opts.keyPassphrase ? String(opts.keyPassphrase) : undefined,\n };\n break;\n case 'OAUTH':\n if (!opts.password)\n throw new Error('--password (token, or env:VAR) is required for OAUTH auth');\n authBlock = {\n method: 'OAUTH',\n username: String(opts.user),\n token: String(opts.password),\n };\n break;\n case 'EXTERNAL_BROWSER':\n authBlock = { method: 'EXTERNAL_BROWSER', username: String(opts.user) };\n break;\n case 'MFA':\n if (!opts.password) throw new Error('--password is required for MFA auth');\n authBlock = {\n method: 'MFA',\n username: String(opts.user),\n password: String(opts.password),\n };\n break;\n default:\n throw new Error(`Unsupported auth method: ${auth}`);\n }\n const profile: ConnectionProfile = {\n name: String(opts.name),\n account: String(opts.account),\n auth: authBlock,\n role: opts.role ? String(opts.role) : undefined,\n warehouse: opts.warehouse ? String(opts.warehouse) : undefined,\n database: opts.database ? String(opts.database) : undefined,\n schema: opts.schema ? String(opts.schema) : undefined,\n };\n await upsertProfile(profile);\n logger.success(`Saved profile \"${profile.name}\".`);\n });\n\n cmd\n .command('remove')\n .description('Remove a connection profile.')\n .argument('<name>')\n .action(async (name) => {\n const ok = await removeProfile(String(name));\n if (ok) logger.success(`Removed profile \"${name}\".`);\n else logger.warn(`No profile named \"${name}\".`);\n });\n\n cmd\n .command('test')\n .description('Test connectivity for a profile.')\n .argument('<name>')\n .action(async (name) => {\n const profile = await getProfile(String(name));\n const conn = new SnowflakeConnection(profile);\n try {\n const result = await conn.test();\n logger.success(`OK — Snowflake ${result.version}`);\n } finally {\n await conn.disconnect();\n }\n });\n\n return cmd;\n}\n","/**\n * `sdt 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 * Subcommands:\n * - `rename` — record a RENAME_OBJECT or RENAME_COLUMN op\n * - `move` — record a MOVE_OBJECT op (different schema / database)\n * - `list` — list operations in the log\n * - `remove` — drop an op by id\n *\n * The compare engine reads the log via `applyRefactorLogToResult` (DDT has it;\n * SDT consumes the same shape and the integration is wired in v0.4 polish).\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport {\n appendOperation,\n loadRefactorLog,\n saveRefactorLog,\n REFACTOR_LOG_VERSION,\n extractCte,\n planRenameObject,\n applyRenamePlan,\n planMoveObject,\n buildRefactorDiff,\n renderRefactorDiffMarkdown,\n type RefactorLog,\n type RefactorOperation,\n type ExtractCteResult,\n type RenameSource,\n type RenameObjectPlan,\n type MoveObjectPlanResult,\n} from '@sdt-tools/core/refactoring';\nimport { logger } from '../util/logger.js';\n\nconst DEFAULT_LOG = './refactor.json';\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<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. DB.SCHEMA.TABLE)')\n .requiredOption('--new-name <name>', 'New name for the object')\n .requiredOption('--object-type <type>', 'Snowflake object type (TABLE, VIEW, PROCEDURE, …)')\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 logger.info(\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 logger.success(\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 / database — recorded as MOVE_OBJECT.')\n .requiredOption('--from <fqn>', 'Old FQN (e.g. OLDDB.OLDSCHEMA.NAME)')\n .requiredOption('--to <fqn>', 'New FQN')\n .requiredOption('--object-type <type>', 'Snowflake 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 logger.info(`[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 logger.success(`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 database.\"',\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 database ANALYTICS_PROD\"). Mutually exclusive with --database.',\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-database audits (\"--database-contains-any ANALYTICS,RAW,STG\" finds every refactor on a database whose name embeds any of three keywords in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --database and --not-database.',\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 database 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.',\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 database name (\"--database-contains-all ANALYTICS,PROD\" finds every refactor on a database 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.',\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 databases whose name contains BOTH analytics and prod, keeping databases 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.',\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 database-naming-convention audits across multi-tenant deployments (\\\"--database-regex '^(ANALYTICS|REPORTING)_(PROD|STG)$'\\\" finds every refactor on an analytics-or-reporting production-or-staging database — 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 database — 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 database-tier audits (\"--database-prefix ANALYTICS_\" finds every refactor on analytics databases while excluding mid-name *ANALYTICS_* matches that the --database substring filter would falsely include).',\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 databases without false-matching mid-name *ANALYTICS_* databases). Mutually exclusive with --database-prefix.',\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 databases in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --database-prefix and --not-database-prefix.',\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 databases in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --database-prefix, --not-database-prefix, and --database-prefixes.',\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 databases 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 databases). 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 databases 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 databases 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 database 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 databases in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --database-exact and --not-database-exact.',\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 databases in a single pass). Whitespace around commas is trimmed. Mutually exclusive with --database-exact, --not-database-exact, and --databases.',\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 database without false-matching ANALYTICS_PROD / AUDIT_ANALYTICS). Mutually exclusive with --database-exact.',\n )\n .option(\n '--name-min-length <n>',\n 'Filter to ops whose target object.name length is >= n (case-insensitive — 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 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 database 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).',\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 database 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.',\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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.error(`refactor list: --id-prefixes must contain at least one non-empty value.`);\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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.error(`refactor list: --id-suffixes must contain at least one non-empty value.`);\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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.error(`refactor list: --object-types must be a non-empty comma-separated list.`);\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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.error(`refactor list: --not-schemas 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?.schema === 'string' &&\n !excludeSet.has(o.object.schema.toLowerCase()),\n );\n }\n if (opts.databasePrefix !== undefined && opts.notDatabasePrefix !== undefined) {\n logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.error(`refactor list: --quarter and --quarters are mutually exclusive; pick one.`);\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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.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 logger.info(`Refactor log summary: ${logPath} (${operations.length} op(s) total)`);\n const kinds = Object.keys(byType).sort();\n for (const kind of kinds) {\n logger.info(` ${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 logger.info(\n `Refactor log: ${logPath} (${operations.length} op(s)${\n annotations.length > 0 ? `, ${annotations.join(', ')}` : ''\n })`,\n );\n }\n for (const op of operations) {\n logger.info(` [${op.timestamp}] ${op.type} ${describe(op)} id=${op.id}`);\n if (op.note) logger.info(` 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. DB.SCH.OLD_TABLE)')\n .requiredOption('--to <fqn>', 'New fully-qualified name (e.g. DB.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 'Snowflake 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 logger.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 logger.error('rename-object: --log requires --object-type <type>');\n process.exitCode = 1;\n return;\n }\n const sources: 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: 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 logger.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 // SOURCE_NAME_NOT_FOUND is informational, not fatal — exit 0\n // so a clean rerun on an already-renamed tree is harmless.\n if (opts.json) {\n process.stdout.write(JSON.stringify(planJsonPayload) + '\\n');\n } else {\n logger.info(\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 logger.error(\n `rename-object refused: ${blockingConflicts.length} blocking conflict(s).`,\n );\n for (const c of blockingConflicts) {\n logger.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 const op = {\n type: 'RENAME_OBJECT' as const,\n object: {\n ...(plan.from.database ? { database: plan.from.database } : {}),\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 logger.info(\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 logger.info(` ${change.path} — ${change.occurrences.length} occurrence(s)`);\n }\n if (recordedLogPath !== undefined) {\n logger.info(`Recorded RENAME_OBJECT op in ${recordedLogPath}.`);\n }\n if (!opts.apply) {\n logger.info('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 databases / 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 (database.schema.name)')\n .requiredOption(\n '--to <container>',\n 'Destination container — 1-part (newdb) or 2-part (newdb.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 'Snowflake 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 logger.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 logger.error('move-object: --log requires --object-type <type>');\n process.exitCode = 1;\n return;\n }\n const sources: 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: 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 logger.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 logger.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 logger.info(\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 logger.error(`move-object refused: ${blockingConflicts.length} blocking conflict(s).`);\n for (const c of blockingConflicts) {\n logger.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 // toFqn was constructed by planMoveObject as `<db|cat>.<sch>.<name>` —\n // re-split into the RefactorOperation FullyQualifiedName shape.\n const toParsed = splitFqn(plan.toFqn);\n const op = {\n type: 'MOVE_OBJECT' as const,\n object: {\n ...(plan.from.database ? { database: plan.from.database } : {}),\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 ...(plan.from.database ? { database: plan.from.database } : {}),\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 logger.info(\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 logger.info(` ${change.path} — ${change.occurrences.length} occurrence(s)`);\n }\n if (recordedLogPath !== undefined) {\n logger.info(`Recorded MOVE_OBJECT op in ${recordedLogPath}.`);\n }\n if (!opts.apply) {\n logger.info('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 logger.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: 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 logger.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 logger.success(\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 logger.error(`No operation with id ${opts.id} in ${logPath}`);\n process.exitCode = 1;\n return;\n }\n await saveRefactorLog(logPath, { ...log, operations: remaining });\n logger.success(`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: 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","/**\n * `sdt import` — convert artifacts from other tools into an `.sdtproj`.\n *\n * Sources (all v0.x stubs):\n * - schemachange (V*.sql / R__*.sql tree)\n * - snowddl (YAML config tree)\n * - sqlpackage-dacpac (SQL Server `.dacpac`)\n * - snowflake-account (live account → project, like `extract` + skeleton)\n * - terraform-state (`.tfstate` from Snowflake-Labs/snowflake provider)\n * - sql-files (flat dir of `.sql`)\n */\nimport { Command } from 'commander';\n\nimport { importers as importersApi } from '@sdt-tools/core';\nimport { logger } from '../util/logger.js';\n\nexport function importCommand(): Command {\n return new Command('import')\n .description('Convert artifacts from other tools into an SDT project.')\n .requiredOption(\n '--from <source>',\n 'Source format (schemachange, snowddl, sqlpackage-dacpac, snowflake-account, snowflake-dcm, terraform-state, sql-files)',\n )\n .requiredOption('--source-path <path>', 'Source artifact path (file or directory)')\n .requiredOption('--output <dir>', 'Output directory for the generated SDT project')\n .option('--connection <profile>', 'Connection profile (required for snowflake-account)')\n .action(\n async (opts: { from: string; sourcePath: string; output: string; connection?: string }) => {\n const source = opts.from as Parameters<typeof importersApi.getImporter>[0];\n const importer = importersApi.getImporter(source);\n const result = await importer.import({\n sourcePath: opts.sourcePath,\n outputDir: opts.output,\n connectionProfile: opts.connection,\n });\n logger.info(\n `Imported ${result.filesCreated} files. Project written to ${result.projectPath}`,\n );\n for (const w of result.warnings) logger.warn(w);\n },\n );\n}\n","/**\n * `sdt format` — normalize SQL formatting in project source files.\n *\n * Safety properties (see @sdt-tools/core/format):\n * 1. Pre-format validation: refuses to touch files whose SQL doesn't\n * tokenize (unclosed string / comment / dollar-quote / unbalanced\n * parens). Diagnostics are reported with line/column.\n * 2. Functional identity: every non-whitespace token in the input\n * appears in the output, in the same order, with identical text —\n * except KEYWORD/BUILTIN tokens whose case may be normalized per\n * the configured style.\n * 3. Idempotence: format(format(x)) === format(x).\n *\n * `--engine legacy` is retained as a deprecated alias of `v2` so existing\n * scripts keep working; it emits a one-line deprecation notice and then\n * runs v2. Will be removed in a future major.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport {\n FORMAT_STYLE_PRESET_NAMES,\n format,\n getFormatPreset,\n isFormatStylePreset,\n mergeFormatStyle,\n} from '@sdt-tools/core/format';\nimport type { FormatStyle } from '@sdt-tools/core/format';\nimport { logger } from '../util/logger.js';\n\nexport function formatCommand(): Command {\n return new Command('format')\n .description(\n 'Format SQL files using the tokenizer-based v2 engine (refuse-on-invalid, idempotent, token-faithful).',\n )\n .option('--check', 'Exit with code 1 if any file is not formatted.')\n .option(\n '--engine <v>',\n 'Formatter engine: \"v2\" (default; tokenizer-based) | \"legacy\" (deprecated alias of v2).',\n 'v2',\n )\n .option(\n '-p, --project <path>',\n 'Path to the .sdtproj (used to find the file set + load formatStyle).',\n )\n .option('--in-place', 'Write formatted output back to the file. Default: stdout.', false)\n .option(\n '--dbt',\n 'Force dbt-mode on: 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: feed Jinja text directly to the formatter (almost always wrong on dbt models; opt-out for power users with pre-compiled SQL).',\n )\n .option(\n '--style <preset>',\n `Apply a named layout preset before any project-level overrides: ${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 .argument('[files...]', 'Specific files to format. Required if --project is not given.')\n .action(\n async (\n files: string[],\n opts: {\n check?: boolean;\n engine?: string;\n project?: string;\n inPlace?: boolean;\n dbt?: boolean;\n style?: string;\n },\n ) => {\n const engine = String(opts.engine ?? 'v2').toLowerCase();\n if (engine !== 'v2' && engine !== 'legacy') {\n throw new Error(\n `Unknown --engine: ${opts.engine}. Use \"v2\" or \"legacy\" (deprecated alias).`,\n );\n }\n if (engine === 'legacy') {\n logger.warn(\n '--engine legacy is a deprecated alias of --engine v2 and will be removed in a future major. Running v2.',\n );\n }\n\n // v2 engine path.\n const targets = await collectTargets(files, opts.project);\n if (targets.length === 0) {\n logger.error('No files to format. Pass file paths as arguments or --project <path>.');\n process.exitCode = 1;\n return;\n }\n\n // Project-level style override comes from .sdtproj (formatStyle field).\n // For now, just use defaults — the v0 engine only honors casing.\n // DBTC.4 — --dbt / --no-dbt resolves to FormatStyle.experimental.dbtMode.\n // Commander's --no-dbt yields opts.dbt === false; absent flag yields\n // undefined (default auto-detect).\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 overrides: FormatStyle = dbtMode ? { experimental: { dbtMode } } : {};\n const style: FormatStyle = mergeFormatStyle(preset, overrides);\n\n let changedCount = 0;\n let refusedCount = 0;\n for (const file of targets) {\n const input = await fs.readFile(file, 'utf8');\n const result = format(input, style);\n if (result.refused) {\n logger.error(\n `✗ ${file} — refused (${result.diagnostics.filter((d) => d.severity === 'ERROR').length} error(s)):`,\n );\n for (const d of result.diagnostics.filter((d) => d.severity === 'ERROR')) {\n logger.error(` L${d.line}:${d.column} [${d.code}] ${d.message}`);\n }\n refusedCount++;\n process.exitCode = 1;\n continue;\n }\n if (opts.check) {\n if (result.changed) {\n logger.warn(`! ${file} — would reformat`);\n changedCount++;\n process.exitCode = 1;\n } else {\n logger.info(` ${file} — ok`);\n }\n continue;\n }\n if (opts.inPlace) {\n if (result.changed) {\n await fs.writeFile(file, result.output, 'utf8');\n logger.info(`✓ ${file} — reformatted`);\n changedCount++;\n } else {\n logger.info(` ${file} — already formatted`);\n }\n } else {\n // Default: print to stdout. Useful for pipelines.\n process.stdout.write(result.output);\n if (!result.output.endsWith('\\n')) process.stdout.write('\\n');\n }\n for (const d of result.diagnostics.filter((d) => d.severity === 'WARNING')) {\n logger.warn(` L${d.line}:${d.column} [${d.code}] ${d.message}`);\n }\n }\n\n if (opts.check && changedCount === 0 && refusedCount === 0) {\n logger.info(`All ${targets.length} file(s) already formatted.`);\n }\n },\n );\n}\n\nasync function collectTargets(files: string[], project?: string): Promise<string[]> {\n if (files.length > 0) {\n return files.map((f) => path.resolve(f));\n }\n if (!project) return [];\n // Minimal project-aware mode: walk the project root for *.sql files.\n // Full project-aware glob handling is deferred to a follow-up — for\n // now, scan the directory containing the .sdtproj.\n const root = path.dirname(path.resolve(project));\n const out: string[] = [];\n await walk(root, out);\n return out;\n}\n\nasync function walk(dir: string, out: string[]): Promise<void> {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const e of entries) {\n if (e.name === 'node_modules' || e.name === 'dist' || e.name.startsWith('.')) continue;\n const full = path.join(dir, e.name);\n if (e.isDirectory()) {\n await walk(full, out);\n } else if (e.isFile() && e.name.endsWith('.sql')) {\n out.push(full);\n }\n }\n}\n","/**\n * `sdt completion <shell>` — print shell completion script for bash | zsh | fish | powershell.\n *\n * v0.1 prints a minimal completion script that lists top-level commands. The\n * full surface (option flags, dynamic profile names from `~/.sdt/profiles.json`)\n * is wired in v0.2.\n */\nimport { Command } from 'commander';\n\nimport { logger } from '../util/logger.js';\n\nconst COMMANDS = [\n 'init',\n 'extract',\n 'build',\n 'publish',\n 'compare',\n 'drift',\n 'validate',\n 'connection',\n 'refactor',\n 'import',\n 'format',\n 'completion',\n 'telemetry',\n 'license',\n];\n\nexport function completionCommand(): Command {\n return new Command('completion')\n .description('Print shell completion script (bash, zsh, fish, powershell).')\n .argument('<shell>', 'Shell: bash | zsh | fish | powershell')\n .action((shell: string) => {\n switch (shell) {\n case 'bash':\n process.stdout.write(bashCompletion());\n break;\n case 'zsh':\n process.stdout.write(zshCompletion());\n break;\n case 'fish':\n process.stdout.write(fishCompletion());\n break;\n case 'powershell':\n case 'pwsh':\n process.stdout.write(powershellCompletion());\n break;\n default:\n logger.error(`Unsupported shell: ${shell}. Use bash | zsh | fish | powershell.`);\n process.exitCode = 1;\n }\n });\n}\n\nfunction bashCompletion(): string {\n return `# sdt bash completion\n_sdt_completion() {\n local cur prev cmds\n cur=\"\\${COMP_WORDS[COMP_CWORD]}\"\n cmds=\"${COMMANDS.join(' ')}\"\n COMPREPLY=( $(compgen -W \"$cmds\" -- \"$cur\") )\n}\ncomplete -F _sdt_completion sdt\n`;\n}\n\nfunction zshCompletion(): string {\n return `#compdef sdt\n_sdt() {\n local -a cmds\n cmds=(${COMMANDS.map((c) => `'${c}:'`).join(' ')})\n _describe 'sdt commands' cmds\n}\n_sdt \"$@\"\n`;\n}\n\nfunction fishCompletion(): string {\n return (\n COMMANDS.map((c) => `complete -c sdt -f -n '__fish_use_subcommand' -a '${c}'`).join('\\n') + '\\n'\n );\n}\n\nfunction powershellCompletion(): string {\n return `Register-ArgumentCompleter -Native -CommandName sdt -ScriptBlock {\n param($wordToComplete, $commandAst, $cursorPosition)\n @(${COMMANDS.map((c) => `'${c}'`).join(', ')}) | Where-Object { $_ -like \"$wordToComplete*\" } | ForEach-Object {\n [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)\n }\n}\n`;\n}\n","/**\n * `sdt telemetry on|off|status` — opt-in / opt-out of usage telemetry AND\n * automatic error reporting (ERR.2: one consent governs both).\n *\n * Preference is stored in `~/.sdt/telemetry.json`; the error-reporting\n * consent in `~/.sdt/error-reporting.json`. Env vars (`DO_NOT_TRACK`,\n * `SDT_TELEMETRY=0`, `CI`) always win — they disable both regardless of\n * the stored preference. See docs/SECURITY.md for what's collected.\n */\nimport { Command } from 'commander';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { homedir } from 'node:os';\n\nimport { errorReport, telemetry } from '@sdt-tools/core';\nimport { logger } from '../util/logger.js';\n\n/** Hermetic override for tests — mirrors `SDT_TRIAL_PATH` / `SDT_ERROR_CONSENT_PATH`. */\nfunction prefPath(): string {\n return process.env['SDT_TELEMETRY_PREF_PATH'] ?? join(homedir(), '.sdt', 'telemetry.json');\n}\n\ninterface StoredPreference {\n pref: 'on' | 'off' | 'unset';\n updatedAt: string;\n}\n\nexport function telemetryCommand(): Command {\n const cmd = new Command('telemetry').description(\n 'Control opt-in usage telemetry and automatic error reporting.',\n );\n\n cmd\n .command('on')\n .description('Enable telemetry + automatic error reporting.')\n .action(async () => {\n await writePref('on');\n await errorReport.writeConsent('on');\n logger.info('Automatic error reporting enabled.');\n });\n cmd\n .command('off')\n .description('Disable telemetry + automatic error reporting.')\n .action(async () => {\n await writePref('off');\n await errorReport.writeConsent('off');\n logger.info('Automatic error reporting disabled.');\n logger.warn(errorReport.CONSENT_WARNING);\n });\n cmd\n .command('status')\n .description('Show current telemetry + error-reporting state.')\n .action(async () => {\n const stored = await readPref();\n const enabled = telemetry.isTelemetryEnabled(stored.pref);\n logger.info(`Stored preference: ${stored.pref}`);\n logger.info(`Currently enabled: ${enabled}`);\n if (process.env.CI === 'true') logger.info('Detected CI=true → telemetry forced off.');\n if (process.env.DO_NOT_TRACK === '1')\n logger.info('Detected DO_NOT_TRACK=1 → telemetry forced off.');\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 logger.info(\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 logger.info(\n `Locally captured errors: ${spooled.length} distinct (${occurrences} occurrences) awaiting ${reportingEnabled ? 'upload' : 'consent'}.`,\n );\n }\n if (!reportingEnabled) logger.dim(` ${errorReport.CONSENT_WARNING}`);\n });\n\n return cmd;\n}\n\nasync function writePref(pref: 'on' | 'off'): Promise<void> {\n const file = prefPath();\n await mkdir(dirname(file), { recursive: true });\n const stored: StoredPreference = { pref, updatedAt: new Date().toISOString() };\n await writeFile(file, JSON.stringify(stored, null, 2) + '\\n', 'utf8');\n logger.info(`Telemetry preference set to \"${pref}\".`);\n}\n\nasync function readPref(): Promise<StoredPreference> {\n const file = prefPath();\n if (!existsSync(file)) return { pref: 'unset', updatedAt: '' };\n try {\n const raw = await readFile(file, 'utf8');\n return JSON.parse(raw) as StoredPreference;\n } catch {\n return { pref: 'unset', updatedAt: '' };\n }\n}\n","/**\n * `sdt license show|set|clear` — manage the local license-key file.\n * Open-core, offline, warn-mode (this revision never blocks; missing Pro\n * license only prints a warning when running Pro features).\n *\n * Mirrors `ddt license` in shape.\n */\nimport { promises as fs } from 'node:fs';\nimport { homedir } from 'node:os';\nimport path from 'node:path';\nimport { Command } from 'commander';\n\nimport { license as licenseApi } from '@sdt-tools/core';\nimport { logger } from '../util/logger.js';\n\nexport function licenseCommand(): Command {\n const cmd = new Command('license').description(\n 'Manage the SDT license key (open-core, offline, warn-mode in v0.1).',\n );\n\n cmd\n .command('show')\n .description('Show the currently loaded license.')\n .action(async () => {\n const lic = await licenseApi.loadLicense();\n logger.info(licenseApi.describeLicense(lic));\n });\n\n cmd\n .command('set')\n .description('Install a license JWT to ~/.sdt/license.jwt.')\n .requiredOption('--jwt <token>', 'The full JWT (3 dot-separated base64url parts).')\n .action(async (opts: { jwt: string }) => {\n const target = process.env['SDT_LICENSE_PATH'] ?? path.join(homedir(), '.sdt', '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 licenseApi.loadLicense();\n logger.info(`Wrote ${target}.`);\n logger.info(licenseApi.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['SDT_LICENSE_PATH'] ?? path.join(homedir(), '.sdt', 'license.jwt');\n try {\n await fs.unlink(target);\n logger.info(`Removed ${target}. Now running free tier.`);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n logger.info(`No license file at ${target}; already on free tier.`);\n } else {\n throw err;\n }\n }\n });\n\n return cmd;\n}\n","/**\n * `sdt trial start|status|reset` — manage the local 30-day Pro trial.\n * Mirrors `ddt trial` in shape (PIL.1 + PIL.4).\n */\nimport { Command } from 'commander';\nimport { license } from '@sdt-tools/core';\nimport { logger } from '../util/logger.js';\n\nexport function trialCommand(): Command {\n const cmd = new Command('trial').description(\n 'Manage the SDT 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 `sdt 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 SDT_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 * `sdt pilot register|status` — manage pilot program registration.\n * Mirrors `ddt pilot` in shape (PIL.2).\n */\nimport { Command } from 'commander';\nimport { license } from '@sdt-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 SDT pilot program (90-day Pro access for early adopters).',\n );\n\n cmd\n .command('register')\n .description('Register for the SDT pilot program.')\n .requiredOption('--email <addr>', 'Your email address.')\n .action(async (opts: { email: string }) => {\n logger.info('Registering for the SDT 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 ~/.sdt/license.jwt.');\n logger.info('Run `sdt 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","import path from 'node:path';\nimport { Command } from 'commander';\nimport {\n loadSuite,\n newSuiteTemplate,\n saveSuite,\n validateSuite,\n type SuiteFinding,\n} from '@sdt-tools/core/project';\nimport { license as licenseApi } from '@sdt-tools/core';\nimport { logger } from '../util/logger.js';\n\nasync function warnIfMissingLicense(feature: licenseApi.ProFeature): Promise<void> {\n const lic = await licenseApi.loadLicense();\n const r = licenseApi.checkProFeature(lic, feature);\n if (r.warning) logger.warn(`[Pro] ${r.warning}`);\n}\n\n/**\n * `sdt suite` — manage and validate a `.sdtsuite` file, the collection of\n * `.sdtproj` projects that compose into one Snowflake target.\n *\n * Subcommands:\n * init — scaffold a new .sdtsuite from a list of project paths\n * validate — run the 5 suite-level checks (ownership, refs, cycles,\n * coverage, deploy order)\n * compare — alias for `sdt compare`, run on each suite project in\n * deploy order (forwards each compare to a target)\n * publish — alias for `sdt publish`, run on each suite project in\n * deploy order (sequential, fail-fast)\n *\n * Pro-tier feature.\n */\nexport function suiteCommand(): Command {\n const cmd = new Command('suite').description(\n 'Manage a .sdtsuite — a collection of .sdtproj 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 .sdtsuite file from a list of project paths.')\n .requiredOption('--out <path>', 'Where to write the new .sdtsuite 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.sdtproj',\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 logger.success(`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 .sdtsuite: ownership conflicts, refs, cycles, deploy order.')\n .argument('<suite>', 'Path to a .sdtsuite 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 logger.info(`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 logger.info(` ${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 logger.info(` [${tag}] ${f.code}: ${f.message}`);\n }\n if (deployOrder.length > 0) {\n logger.info(` Deploy order: ${deployOrder.join(' → ')}`);\n } else {\n logger.error(` Suite is undeployable (cycle or invalid order).`);\n }\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 { renderDocsReport, renderErdMarkdown, renderErd3dHtml } from '@sdt-tools/core/compare';\nimport { loadProject, parseProjectModel } from '@sdt-tools/core/project';\nimport { readPac } from '@sdt-tools/core/pac';\nimport { ai, comments } from '@sdt-tools/core';\nimport { buildDocsPublishPlan, renderDocsWorkflowYaml, searchDocs } from '@sdt-tools/core/docs';\nimport type { AnySnowflakeObject } from '@sdt-tools/core/model';\n\n/**\n * `sdt docs` — auto-generate HTML schema docs from a `.sdtproj` or\n * `.sdtpac`. dbt-docs-style: database → 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 .sdtproj or .sdtpac.')\n .requiredOption('--source <path>', '.sdtproj or .sdtpac 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 (table-level + column-level) and emit ALTER … COMMENT SQL.',\n false,\n )\n .option(\n '--augment-out <path>',\n 'When --augment-comments is set, write the ALTER 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>', '.sdtproj or .sdtpac 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 .sdtproj or .sdtpac.')\n .argument('<query>', 'Search query string.')\n .requiredOption('--source <path>', '.sdtproj or .sdtpac 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 * `sdt erd` — auto-generate an ER diagram from a `.sdtproj` or `.sdtpac`.\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 .sdtproj or .sdtpac.',\n )\n .requiredOption('--source <path>', '.sdtproj or .sdtpac 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<AnySnowflakeObject[]> {\n if (sourcePath.endsWith('.sdtpac')) {\n const pacContents = await readPac(sourcePath);\n return pacContents.model as AnySnowflakeObject[];\n }\n const loaded = await loadProject(sourcePath);\n const parsed = await parseProjectModel(loaded);\n return parsed as AnySnowflakeObject[];\n}\n","/**\n * `sdt mcp` — Model Context Protocol server (stdio transport).\n *\n * Exposes SDT'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. The server speaks JSON-RPC 2.0 over newline-delimited\n * JSON on stdio — that's the MCP spec.\n *\n * To wire into Claude Desktop / Cursor / etc., add to the MCP config:\n *\n * {\n * \"mcpServers\": {\n * \"sdt\": { \"command\": \"sdt\", \"args\": [\"mcp\"] }\n * }\n * }\n *\n * Tools exposed:\n * - sdt.validate — schema check on a .sdtproj\n * - sdt.compare — pac↔pac or project↔pac diff (offline)\n * - sdt.docs — generate HTML schema docs\n * - sdt.erd — generate Mermaid ER diagram (Markdown)\n * - sdt.safety_assess — classify a diff's safety findings\n * - sdt.narrate_diff — structured payload (diff + safety + prompt\n * scaffold) so the calling agent's LLM can\n * generate a plain-English narration.\n * - sdt.detect_pii — scan a project/pac for likely PII columns\n * (email/phone/ssn/dob/credit-card/etc.).\n * - sdt.suggest_safer — for every UNRECOVERABLE/DESTRUCTIVE\n * finding on a diff, return the\n * saferAlternatives entries from the safety\n * catalog.\n * - sdt.feature_search — search the SDT 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} from '@sdt-tools/core/compare';\nimport { loadProject, parseProjectModel, discoverObjectFiles } from '@sdt-tools/core/project';\nimport { readPac } from '@sdt-tools/core/pac';\nimport { assess, explainFinding } from '@sdt-tools/core/safety';\nimport { detectPiiCandidates } from '@sdt-tools/core/pii';\nimport type { AnySnowflakeObject } from '@sdt-tools/core/model';\nimport { features } from '@sdt-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 = 'sdt';\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: 'sdt.validate',\n description:\n 'Validate a .sdtproj file: parse JSON, check schema with zod, list object files. Returns a JSON summary of project structure and any validation errors.',\n inputSchema: {\n type: 'object',\n properties: {\n projectPath: { type: 'string', description: 'Absolute path to a .sdtproj 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: 'sdt.compare',\n description:\n 'Compare two .sdtpac 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 .sdtpac.' },\n targetPac: { type: 'string', description: 'Absolute path to the target .sdtpac.' },\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: 'sdt.docs',\n description:\n 'Generate self-contained HTML schema documentation from a .sdtproj or .sdtpac. Returns the HTML body as a string.',\n inputSchema: {\n type: 'object',\n properties: {\n source: { type: 'string', description: 'Absolute path to a .sdtproj or .sdtpac.' },\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: 'sdt.erd',\n description: 'Generate a Mermaid ER diagram (Markdown) from a .sdtproj or .sdtpac.',\n inputSchema: {\n type: 'object',\n properties: {\n source: { type: 'string', description: 'Absolute path to a .sdtproj or .sdtpac.' },\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: 'sdt.safety_assess',\n description:\n 'Given two .sdtpac 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 .sdtpac (the desired state).' },\n targetPac: {\n type: 'string',\n description: 'Target .sdtpac (current state to migrate from).',\n },\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 = assess(diff);\n return JSON.stringify(assessment, null, 2);\n },\n },\n {\n name: 'sdt.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 .sdtpac (desired state).' },\n targetPac: { type: 'string', description: 'Target .sdtpac (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 = 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 Snowflake DBA 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: 'sdt.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 .sdtproj or .sdtpac.' },\n },\n required: ['source'],\n },\n handler: async (args) => {\n const model = await loadModel(String(args.source));\n const candidates = detectPiiCandidates(model);\n return JSON.stringify({ count: candidates.length, candidates }, null, 2);\n },\n },\n {\n name: 'sdt.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 to _archived_<ts> 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 .sdtpac (desired).' },\n targetPac: { type: 'string', description: 'Target .sdtpac (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 = assess(diff);\n const dangerous = [...assessment.unrecoverable, ...assessment.destructive];\n const suggestions = dangerous.map((f) => {\n const explanation = 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: 'sdt.feature_search',\n description:\n 'Search the SDT 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.SDT_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<AnySnowflakeObject[]> {\n const abs = path.resolve(sourcePath);\n if (abs.endsWith('.sdtpac')) {\n const pacContents = await readPac(abs);\n return pacContents.model as AnySnowflakeObject[];\n }\n const loaded = await loadProject(abs);\n const parsed = await parseProjectModel(loaded);\n return parsed as AnySnowflakeObject[];\n}\n\nexport function mcpCommand(): Command {\n const cmd = new Command('mcp');\n cmd\n .description(\n 'Start the SDT 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 * `sdt ai` — configure + test the AI provider adapter.\n *\n * Subcommands:\n * sdt ai status — show current config (provider, model, key source)\n * sdt ai test — round-trip a hello-world prompt to confirm the\n * provider works end-to-end\n * sdt ai usage — summarize ai-usage.json (today + this month)\n *\n * Phase-1 of the AI rollout (see docs/AI_FEATURES.md). Higher-level\n * features (`compare --explain`, safer-alternative suggester, etc.)\n * land in Phase 2+ and call `ai.complete()` from `@sdt-tools/core/ai`.\n */\nimport { Command } from 'commander';\nimport { ai } from '@sdt-tools/core';\nimport { logger } from '../util/logger.js';\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 logger.success('AI provider config (configured):');\n logger.dim(` provider: ${config.provider}`);\n logger.dim(` model: ${config.model}`);\n logger.dim(` endpoint: ${config.endpoint ?? '(provider default)'}`);\n logger.dim(` apiKey: ${apiKey ? '✓ resolved' : '✗ not set'}`);\n logger.dim(` maxTokens: ${config.maxTokens ?? '(provider default)'}`);\n logger.dim(` temperature: ${config.temperature ?? '(provider default)'}`);\n logger.dim(\n ` preferLocal: ${config.preferLocal !== false ? 'true (local-first)' : 'false (cloud only)'}`,\n );\n logger.dim(` configPath: ${ai.defaultConfigPath()}`);\n\n if (config.preferLocal !== false) {\n const probe = await ai.detectOllamaAvailability({ fetch: globalThis.fetch });\n logger.success('Local Ollama probe:');\n if (probe.available) {\n const best = ai.pickBestLocalModel(probe.models);\n logger.dim(` status: ✓ available at ${probe.endpoint}`);\n logger.dim(` models: ${probe.models.join(', ') || '(none pulled)'}`);\n logger.dim(` selected: ${best ?? '(none)'}`);\n logger.success('Effective routing: Ollama (local, zero cloud cost)');\n } else {\n logger.dim(` status: ✗ unavailable (${probe.reason})`);\n logger.dim(` fallback: ${config.provider} / ${config.model}`);\n logger.success(`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 logger.success(`Response from ${result.provider} (${result.model}):`);\n console.log(result.text);\n logger.dim(\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 logger.success('AI usage (local ledger):');\n logger.dim(` today: ${today.length} call(s), ~$${todayUsd.toFixed(4)}`);\n logger.dim(` total: ${records.length} call(s), ~$${allUsd.toFixed(4)}`);\n logger.dim(` 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 logger.dim(' features:');\n for (const [feature, count] of [...byFeature.entries()].sort((a, b) => b[1] - a[1])) {\n logger.dim(` ${feature}: ${count}`);\n }\n }\n });\n\n return cmd;\n}\n","/**\n * `sdt explain <query>` — search the options catalog and print details.\n *\n * Examples:\n * sdt explain drop table\n * sdt explain allowNarrowingTypes\n * sdt explain --tag safety\n * sdt explain --safety destructive\n *\n * See `docs/UX_PLAYBOOK.md` §2 for the full design.\n */\nimport { Command } from 'commander';\nimport { options as optionsApi } from '@sdt-tools/core';\nimport type { OptionEntry, SafetyTier } from '@sdt-tools/core/options';\nimport { logger } from '../util/logger.js';\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, 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 (paginated 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 logger.warn(`No matches for: \"${query || `${tag ?? ''} ${safety ?? ''}`.trim()}\"`);\n logger.dim(' Try: sdt explain --list (full catalog)');\n logger.dim(' Try: sdt explain --tag safety (browse a category)');\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 // Group by first tag for a clean overview.\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 * `sdt feedback \"...\"` — submit a feedback / bug / feature-request\n * ticket from inside the tool.\n *\n * Lowest-friction reporting surface. From any terminal:\n *\n * $ sdt feedback \"publish --apply takes 45s before doing anything\"\n * Sent! Reference: #847.\n *\n * Auto-captures (with user consent on first run):\n * - CLI version\n * - OS + platform\n * - License email (if a license is installed)\n * - Last 5 sdt invocations from ~/.sdt/recent.log (if it exists)\n *\n * Writes to a local outbox first (~/.sdt/feedback/<timestamp>.json)\n * so failures don't lose the report. Drains the outbox in the\n * background. Endpoint is configurable; the default is the\n * project's ingest 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 { logger } from '../util/logger.js';\nimport { license } from '@sdt-tools/core';\n\nconst DEFAULT_INGEST_URL =\n process.env.SDT_FEEDBACK_URL ?? 'https://sdt-support.sdt-ddt-tools.workers.dev/ingest';\nconst OUTBOX_DIR = path.join(os.homedir(), '.sdt', '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 SDT 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 logger.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 logger.success('Feedback sent. Thank you!');\n logger.dim(' You should hear back within 1 business day for Pro+ accounts.');\n if (!payload.licenseEmail) {\n logger.dim(' Tip: install a license (`sdt license activate`) so we can reach you.');\n }\n const extended = await license.extendTrial(1);\n if (extended) {\n logger.dim(\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 logger.warn(`Couldn't reach the ingest endpoint: ${message}`);\n const queued = await queueLocally(payload);\n logger.dim(` Queued locally at ${queued}. Will retry on next \\`sdt 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: 'sdt',\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(), '.sdt', 'license');\n const raw = await fs.readFile(licensePath, 'utf8');\n // License is an Ed25519 JWT — sub claim carries the email. Decode the\n // payload section without verifying (we just want the bound email for\n // display).\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(), '.sdt', '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 // First: drain any previously-queued items (best effort).\n await drainOutbox(url);\n // Then send the new one.\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","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 type LintResult,\n type LintRule,\n} from '@sdt-tools/core/deploy';\nimport { dbtCode, interop } from '@sdt-tools/core';\n\n/** DBTC.4 — auto-detect dbt-mode in the lint surface. */\nconst JINJA_OPENER = /\\{\\{|\\{%/;\n\n/**\n * `sdt lint` — scan a SQL script for risky patterns before you run it.\n * Atlas-style migration linting. Sibling of `ddt lint`; SDT rules are\n * Snowflake-flavored (L001-L032 platform-agnostic, S001-S006\n * Snowflake-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>/.sdt/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","/**\n * `sdt features` — browse the SDT 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 * sdt features list Show all features with state (✅ / 🔒 / 🚧).\n * sdt features show <id> Full pitch + unlock path for one feature.\n * sdt features upgrade What each paid tier would unlock for you.\n */\nimport { Command } from 'commander';\nimport { features as featuresApi, license as licenseApi } from '@sdt-tools/core';\nimport { logger } from '../util/logger.js';\n\nexport function featuresCommand(): Command {\n const cmd = new Command('features');\n cmd.description(\n 'Browse SDT 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 tierWidth = Math.max(...rows.map((r) => r.feature.tier.length), 4);\n const nameWidth = Math.max(...rows.map((r) => r.feature.name.length), 4);\n\n // Group output by tier for readability.\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 void tierWidth;\n process.stdout.write(\n '\\nRun `sdt features show <id>` for the full pitch. `sdt 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 logger.error(`Unknown feature id: \"${id}\". Run \\`sdt 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 * `sdt hosts` — browse every host SDT plugs into, with version-support\n * + tailoring notes. Companion to `sdt features`: features tell you\n * what we do; hosts tell you where you can do it.\n *\n * Subcommands:\n * sdt hosts list Tier-ordered table of every host with status.\n * sdt hosts show <id> Full tailoring notes + supported versions.\n */\nimport { Command } from 'commander';\nimport { hosts as hostsApi } from '@sdt-tools/core';\nimport { logger } from '../util/logger.js';\n\nexport function hostsCommand(): Command {\n const cmd = new Command('hosts');\n cmd.description(\n 'Browse every host SDT plugs into — CLI, VS Code, MCP agents, GitHub Actions, 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 process.stdout.write(\n ` ${pad(host.name, nameWidth)} ${hostsApi.hostSummaryLine(host).split(' · ')[1]}\\n`,\n );\n }\n process.stdout.write(\n '\\nRun `sdt 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 logger.error(`Unknown host id: \"${id}\". Run \\`sdt 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","import { promises as fs } from 'node:fs';\nimport { existsSync } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\n\n/**\n * `sdt install-hooks` — install a git pre-commit hook that runs\n * `sdt format --check` + `sdt 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 = '# sdt-managed-hook';\n\nconst HOOK_BODY = `#!/bin/sh\n${HOOK_MARKER} — installed by \\`sdt 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 '*.sdtproj' -not -path '*/node_modules/*' -not -path '*/dist/*' | head -1)\nif [ -z \"$project\" ]; then\n echo \"sdt pre-commit hook: no .sdtproj found (skipping).\"\n exit 0\nfi\n\necho \"sdt pre-commit: validate + format-check on $project\"\n\nif ! command -v sdt >/dev/null 2>&1; then\n echo \"sdt CLI not on PATH. Install with \\`npm i -g @sdt-tools/cli\\`, or remove the hook at .git/hooks/pre-commit.\"\n exit 1\nfi\n\nif ! sdt validate -p \"$project\"; then\n echo \"\"\n echo \"Refusing commit: \\`sdt validate\\` failed.\"\n exit 1\nfi\n\nif ! sdt format -p \"$project\" --check; then\n echo \"\"\n echo \"Refusing commit: some .sql files are not formatted. Run \\`sdt 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 `sdt validate` + `sdt 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 sdt-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 sdt-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 sdt-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 `sdt validate` + `sdt format --check` on every commit.');\n console.log(\n ' Bypass once with `git commit --no-verify`. Remove with `sdt 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 const stat = await fs.stat(candidate);\n if (stat.isDirectory()) return candidate;\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 { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { getProfile, SnowflakeConnection } from '@sdt-tools/core/connection';\nimport { SnowflakeQueryHistoryReader } from '@sdt-tools/core/queryHistory';\nimport { logger } from '../util/logger.js';\nimport type { QueryHistoryEntry } from '@sdt-tools/core/queryHistory';\n\n/**\n * `sdt history` — two modes.\n *\n * 1. **Manifest mode** (default) — read deploy manifests from a\n * directory (written by `sdt publish --apply --manifest <path>`)\n * and show a chronological summary.\n *\n * 2. **Live mode** (triggered by `--last`, `--query`, or `--verify`)\n * — query the Snowflake account's QUERY_HISTORY views via the\n * SnowflakeQueryHistoryReader. Requires `--connection <profile>`.\n */\ninterface Manifest {\n version: 1;\n deployedAt?: string;\n account?: string;\n warehouse?: 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 the live Snowflake QUERY_HISTORY views via --last/--query/--verify.',\n )\n // Manifest mode\n .option(\n '--dir <path>',\n 'Directory containing *.json manifests (manifest mode).',\n './.sdt/history',\n )\n .option(\n '--limit <n>',\n 'Manifest mode: most-recent N entries. Live mode: max rows returned.',\n '20',\n )\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 // Live mode\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 QUERY_ID.')\n .option(\n '--verify <tag>',\n 'Live mode: read all queries tagged with this string. Use the auto-generated tag from `sdt publish --apply` for deploy verification.',\n )\n .option('--since <iso>', 'Live mode: only include entries after this ISO 8601 timestamp.')\n .option(\n '--view <kind>',\n \"Live mode: which view to query — 'session' | 'user' | 'account'. Default 'session'.\",\n 'session',\n )\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 view?: string;\n }) => {\n const isLive =\n opts.last !== undefined || opts.query !== undefined || opts.verify !== undefined;\n if (isLive) {\n await runLive(opts);\n } else {\n await runManifests(opts);\n }\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 ?? './.sdt/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 ACCOUNT 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.account ?? '?').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 view?: string;\n limit?: string;\n json?: boolean;\n fullSql?: boolean;\n}): Promise<void> {\n if (!opts.connection) {\n logger.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 = new SnowflakeConnection(profile);\n await conn.connect();\n try {\n const view = String(opts.view ?? 'session').toLowerCase() as 'session' | 'user' | 'account';\n const reader = new SnowflakeQueryHistoryReader(conn, { defaultView: view });\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 // --last [n]\n const n = typeof opts.last === 'string' ? parseInt(opts.last, 10) || limit : limit;\n // Reuse readByUser with the current user; if that's not set on the\n // reader, the underlying view still respects the current session's\n // user via INFORMATION_SCHEMA semantics.\n entries = await reader.readByUser(profile.auth.username ?? '', {\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 QUERY_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) => 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 * `sdt audit-log emit` — export deploy + compare history records to\n * enterprise audit sinks. Reads `.sdt/history/*.json` (deploys) and\n * `.sdt/history/compare/*.json` (compares, AUDITCMP.1), normalises each\n * record via `@sdt-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, compare, deploy } from '@sdt-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 .sdt/history/*.json (deploys) + .sdt/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 .sdt/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: sdt).')\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: sdt).')\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: 'sdt').\")\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 deploy.loadDeployHistory(opts.workspace);\n const compareRecords = await compare.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}/.sdt/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 { Command } from 'commander';\nimport { pac } from '@sdt-tools/core';\n\n/**\n * `sdt verify <pac>` — recompute checksums and confirm the .sdtpac 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 .sdtpac and confirm every object matches the manifest.')\n .requiredOption('--pac <path>', 'Path to the .sdtpac 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 * `--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 `@sdt-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 `sdt 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 `Databricks/packages/cli/src/util/ai-explain.ts`.\n */\nimport type { Command } from 'commander';\nimport { ai } from '@sdt-tools/core';\nimport { logger } from './logger.js';\n\nexport interface ExplainContext {\n /**\n * Stable feature identifier surfaced to the AI usage telemetry so we\n * can analyze which command surfaces actually drive AI traffic.\n * Convention: `<command>.explain` (e.g. `diagnose.explain`).\n */\n feature: string;\n /**\n * System prompt setting the assistant's persona. Each command picks\n * the wording that matches its role (senior DBA / senior data eng /\n * release-manager / etc.). The default is a generic Snowflake-savvy\n * narrator suitable for most commands.\n */\n systemPrompt?: string;\n}\n\nconst DEFAULT_SYSTEM_PROMPT = `You are a senior Snowflake DBA reviewing structured output from the SDT 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\n/**\n * Attach the `--explain` flag to a command. Idempotent — safe to call on\n * any command, including ones that already define `--explain`\n * (commander will throw, so we guard against double-attach).\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 `sdt ai` to be configured.',\n false,\n );\n return cmd;\n}\n\n/**\n * Run the AI narration step. Call this AFTER the structured output is\n * printed so the user sees the deterministic result first and the AI\n * commentary second.\n *\n * `opts.explain` is the parsed value of the `--explain` flag — when\n * falsy, this is a no-op. The consumer passes a `buildPrompt` callback\n * that returns the user message body; the callback is only invoked when\n * `--explain` is on, so consumers don't pay the prompt-construction cost\n * when AI is off.\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 logger.info('');\n logger.info('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')) logger.info(' ' + line);\n } catch (err) {\n logger.error(' --explain failed: ' + (err instanceof Error ? err.message : String(err)));\n logger.error(\n ' Run `sdt ai status` to verify your AI provider is configured (`sdt 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 { compare, pac, project } from '@sdt-tools/core';\nimport { attachExplainFlag, runExplain } from '../util/ai-explain.js';\n\n/**\n * `sdt graph` — emit an object-dependency DAG (Mermaid or DOT) from a\n * `.sdtproj` or `.sdtpac`. 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 *\n * Mirrors `ddt graph`.\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>', '.sdtproj or .sdtpac 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 .sdtproj or .sdtpac. 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 = compare.buildDependencyGraph(model);\n\n let diff: compare.DependencyGraphDiff | undefined;\n if (opts.compareTo) {\n const otherModel = await loadModel(String(opts.compareTo));\n const otherGraph = compare.buildDependencyGraph(otherModel);\n // Source = \"after\", compareTo = \"before\" → the user is asking\n // \"what did the source side add vs the reference snapshot?\"\n diff = compare.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 = compare.renderGraphMermaid(graph);\n } else if (fmt === 'dot') {\n payload = compare.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${compare.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: compare.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: compare.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: compare.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) {\n if (sourcePath.endsWith('.sdtpac')) {\n const c = await pac.readPac(sourcePath);\n return c.model;\n }\n const loaded = await project.loadProject(sourcePath);\n return await project.parseProjectModel(loaded);\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 type CompareSource,\n} from '@sdt-tools/core/compare';\nimport { ScriptGenerator, colorizeMigrationScript } from '@sdt-tools/core/deploy';\nimport { mergeDeployOptions, loadProject } from '@sdt-tools/core/project';\nimport { readPac } from '@sdt-tools/core/pac';\nimport { safety } from '@sdt-tools/core';\nimport type { DeploymentProfile } from '@sdt-tools/core/project';\nimport { addMappingFlags, buildMappingFromOptions } from '../util/mapping.js';\n\n/**\n * `sdt script` — generate a deploy SQL script for source → target. Mirrors\n * SqlPackage `/Action:Script` / SSDT's \"Generate Script\" affordance. Always\n * offline — does not touch a live Snowflake account.\n *\n * Output formats:\n * - sql (default): human-readable migration script with banner comments\n * - json: raw CompareResult + safety assessment + per-statement\n * metadata, suitable for CI gates or UI rendering\n *\n * Mirrors `ddt script`. To compare against a live account, use\n * `sdt compare` or `sdt publish`.\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 account.',\n )\n .requiredOption('--source <path>', 'Source: .sdtproj or .sdtpac (the desired state).')\n .requiredOption('--target <path>', 'Target: .sdtproj or .sdtpac (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 (`.sdtproj` reads `project.deploymentProfiles`; `.sdtpac` 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(\n '--color <mode>',\n 'Color stdout: auto | always | never. Honors NO_COLOR / SDT_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 (`$(SDT_PROFILE)`,\n // `$(SDT_PROJECT_NAME)`, `$(SDT_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('.sdtproj') || sourcePath.endsWith('.sdtpac')) {\n try {\n if (sourcePath.endsWith('.sdtpac')) {\n const srcPac = await 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 .sdtproj declare any?).'\n : `Available: ${available.join(', ')}.`),\n );\n }\n if (block.variables) profileVariables = { ...block.variables };\n }\n } else if (sourcePath.endsWith('.sdtproj')) {\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 .sdtproj. ` +\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 the user passed --profile, hard-fail. Otherwise best-effort:\n // built-ins stay defaulted on a partial / unreadable source.\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 ? { 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 sdt 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.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('.sdtpac')\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 { Command } from 'commander';\nimport { getProfile, SnowflakeConnection } from '@sdt-tools/core/connection';\nimport {\n SnowflakeExecutor,\n revertStepsFromManifest,\n type DeployManifest,\n} from '@sdt-tools/core/deploy';\n\n/**\n * `sdt revert --manifest <path>` — undo a previous deploy by executing\n * each step's `reverseSql` in reverse order. Manifests come from\n * `sdt publish --apply --manifest <path>` (the JSON deploy manifest\n * captured 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 * Mirrors `Databricks/packages/cli/src/commands/revert.ts`. Use case: a\n * deploy succeeded but something downstream broke; revert it. Use case:\n * drift is detected and you need to roll back to the last-known-good\n * state.\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 `sdt 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.account !== manifest.account) {\n console.error('');\n console.error(\n `WARNING: manifest's account (${manifest.account}) doesn't match the profile's account (${profile.account}).`,\n );\n console.error(\n 'Reverting against a different account 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.account}`);\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 = new SnowflakeConnection(profile);\n let succeeded = 0;\n let failed = 0;\n let irreversible = 0;\n try {\n await conn.connect();\n const executor = new SnowflakeExecutor(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 * `sdt snapshot` — surface the TRUST.1 pre-deploy snapshot registry from\n * the CLI.\n *\n * sdt snapshot list [--root <path>] [--json] [--expired-only]\n * sdt snapshot show <batch-id> [--root <path>] [--json]\n * sdt snapshot prune [--root <path>] [--connection <profile>]\n * [--apply] [--yes] [--out <path>]\n *\n * `publish --apply` writes a registry entry under `.sdt/snapshots/<batchId>.json`\n * every time it takes a pre-deploy CLONE. The TTL is per-batch (default\n * 168h). This command lets an operator inspect batches, audit them, and\n * drop both the snapshot tables and the registry rows when the retention\n * horizon has passed.\n *\n * Mirrors `Databricks/packages/cli/src/commands/snapshot.ts`.\n */\nimport path from 'node:path';\nimport { promises as fs } from 'node:fs';\nimport { Command } from 'commander';\nimport { safety } from '@sdt-tools/core';\nimport { getProfile, SnowflakeConnection } from '@sdt-tools/core/connection';\nimport { splitStatements as coreSplitStatements } from '@sdt-tools/core/deploy';\nimport { logger } from '../util/logger.js';\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 `sdt 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 logger.success(`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 = new SnowflakeConnection(profile);\n try {\n for (const b of expired) {\n for (const stmt of coreSplitStatements(safety.emitPruneSnapshotSql(b).join('\\n')).map(\n (s) => s.sql,\n )) {\n try {\n await conn.query(stmt);\n executed += 1;\n } catch (err) {\n failed += 1;\n const msg = err instanceof Error ? err.message : String(err);\n logger.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 logger.success(\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","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { getProfile, SnowflakeConnection } from '@sdt-tools/core/connection';\nimport { SnowflakeExecutor } from '@sdt-tools/core/deploy';\nimport { discoverSeeds, loadProject, renderSeedMerge } from '@sdt-tools/core/project';\n\n/**\n * `sdt seed` — declare static reference rows next to DDL; engine\n * generates MERGE statements to keep them in sync.\n *\n * Mirrors `Databricks/packages/cli/src/commands/seed.ts`. 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 an account\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 .sdtproj 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/<database>/<schema>/<table>.{json,csv}.',\n );\n return;\n }\n for (const s of seeds) {\n console.log(\n ` ${s.database}.${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 account contact.')\n .requiredOption('-p, --project <path>', 'Path to the .sdtproj file.')\n .option('-o, --out <path>', 'Write to file. Defaults to stdout.')\n .option(\n '--delete-not-in-source',\n 'Prepend a DELETE so target-only rows are removed (Snowflake equivalent of WHEN NOT MATCHED BY SOURCE). 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 .sdtproj 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 'Prepend a DELETE so target-only rows are removed (Snowflake equivalent of WHEN NOT MATCHED BY SOURCE). 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 = new SnowflakeConnection(profile);\n let succeeded = 0;\n let failed = 0;\n try {\n await conn.connect();\n const exec = new SnowflakeExecutor(conn);\n for (const s of seeds) {\n process.stdout.write(`▶ ${s.database}.${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 { promises as fs } from 'node:fs';\nimport { randomUUID } from 'node:crypto';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { lineage, pac, project, columnLineage } from '@sdt-tools/core';\nimport { attachExplainFlag, runExplain } from '../util/ai-explain.js';\n\n/**\n * CLL.7-followup runtime: thread CLI flags + `.sdt/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 / Snowflake VARIANT loaders).\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 ?? 'sdt-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 * `sdt lineage` — extract data-flow lineage from a `.sdtproj` or\n * `.sdtpac` and emit it as Mermaid, DOT, JSON, or Markdown.\n *\n * Distinct from `sdt 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 * Use cases:\n * - \"What does ANALYTICS.GOLD.CUSTOMER_360 depend on?\" (upstream slice)\n * - \"If I drop RAW.STAGING.ORDERS_RAW, what breaks?\" (downstream slice)\n * - \"Embed this graph in our PR template / docs / dashboard.\"\n *\n * Mirrors `ddt lineage`.\n */\nexport function lineageCommand(): Command {\n const cmd = new Command('lineage');\n cmd\n .description('Extract data-flow lineage from a .sdtproj, .sdtpac, or dbt manifest.json.')\n .option('--source <path>', '.sdtproj or .sdtpac 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 / SECURE_VIEW / MATERIALIZED_VIEW / DYNAMIC_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 .sdt/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 .sdt/lineage.json).',\n )\n .option(\n '--emit-openlineage-namespace <ns>',\n 'Override the OpenLineage dataset namespace (default snowflake).',\n )\n .option(\n '--emit-openlineage-job-namespace <ns>',\n 'Override the OpenLineage job.namespace (default sdt). 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, Snowflake VARIANT loaders).',\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(/\\.(sdtproj|sdtpac)$/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 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) {\n if (sourcePath.endsWith('.sdtpac')) {\n const c = await pac.readPac(sourcePath);\n return c.model;\n }\n const loaded = await project.loadProject(sourcePath);\n return await project.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 / SECURE_VIEW / MATERIALIZED_VIEW / DYNAMIC_TABLE — the four object\n * types whose `query: SqlExpression` is what downstream consumers depend\n * on for column-level lineage. CLL.4 entry point.\n */\nfunction collectColumnLineageInputs(model: unknown): columnLineage.ColumnLineageDagInput[] {\n const inputs: columnLineage.ColumnLineageDagInput[] = [];\n const matchTypes = new Set<string>(['VIEW', 'SECURE_VIEW', 'MATERIALIZED_VIEW', 'DYNAMIC_TABLE']);\n // parseProjectModel returns AnySnowflakeObject[]; readPac().model is the\n // same shape. Some legacy pac models nest objects under .objects so we\n // accept either form defensively.\n let flat: Array<{ objectType?: string; fqn?: unknown; query?: unknown }>;\n if (Array.isArray(model)) {\n flat = model as Array<{ objectType?: string; fqn?: unknown; query?: unknown }>;\n } else if (\n model &&\n typeof model === 'object' &&\n Array.isArray((model as { objects?: unknown }).objects)\n ) {\n flat = (model as { objects: Array<{ objectType?: string; fqn?: unknown; query?: unknown }> })\n .objects;\n } else {\n flat = [];\n }\n for (const obj of flat) {\n if (!obj.objectType || !matchTypes.has(obj.objectType)) continue;\n if (typeof obj.query !== 'string' || obj.query.length === 0) continue;\n const fqn =\n typeof obj.fqn === 'string'\n ? obj.fqn\n : obj.fqn && typeof obj.fqn === 'object'\n ? formatFqn(obj.fqn as { database?: string; schema?: string; name?: string })\n : '<unknown>';\n const lineage = columnLineage.extractColumnLineage(obj.query);\n inputs.push({ objectFqn: fqn, lineage });\n }\n return inputs;\n}\n\nfunction formatFqn(fqn: { database?: string; schema?: string; name?: string }): string {\n return [fqn.database, fqn.schema, fqn.name].filter(Boolean).join('.');\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { diagnostics, interop, pac, project } from '@sdt-tools/core';\nimport { attachExplainFlag, runExplain } from '../util/ai-explain.js';\n\n/**\n * `sdt 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 clustering, missing PK)\n * and cost smells (warehouse without AUTO_SUSPEND, long Time Travel)\n * into one ranked report. Every finding ships with a **reasoning**\n * line explaining *why* it matters — readers learn the engineering\n * motivation, not just the patch.\n *\n * Use cases:\n * - Pre-PR check: `sdt diagnose --source <proj> --min-severity warning`\n * - Periodic project audit: weekly cron emitting JSON to a dashboard\n * - Onboarding: a new engineer reads the report to learn what good\n * looks like in this codebase\n *\n * Mirrors `ddt 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>', '.sdtproj or .sdtpac 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 // Non-zero exit when at least one error-severity finding fires so\n // `sdt diagnose` can gate a CI step.\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) {\n if (sourcePath.endsWith('.sdtpac')) {\n const c = await pac.readPac(sourcePath);\n return c.model;\n }\n const loaded = await project.loadProject(sourcePath);\n return await project.parseProjectModel(loaded);\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { ai, aiReview, pac, project, review } from '@sdt-tools/core';\nimport { attachExplainFlag, runExplain } from '../util/ai-explain.js';\n\n/**\n * `sdt review` — produce a senior-DBA Markdown report combining lint,\n * lineage findings, smell findings, cost findings, and safety\n * reasoning. The deliverable a reviewer can paste straight into a PR\n * or an architecture-review meeting.\n *\n * Default mode (project health): pure composition of existing modules —\n * every finding's reasoning + suggestion is generated by\n * `@sdt-tools/core/diagnostics`; the format is the value-add.\n *\n * `--senior-dba` mode (AI Phase 4): takes a compare-result JSON\n * (typically the output of `sdt compare --json`) + a safety-summary\n * JSON + optional target-metadata snapshot + truncated DDL preview,\n * asks the configured AI provider for a senior-DBA verdict, and emits\n * the parsed result as Markdown (or JSON via `--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>', '.sdtproj or .sdtpac 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, 'sdt');\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 Snowflake principal engineer giving a senior-architect verbal 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 // Set exit code on request_changes so CI gates can rely on it.\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) {\n if (sourcePath.endsWith('.sdtpac')) {\n const c = await pac.readPac(sourcePath);\n return c.model;\n }\n const loaded = await project.loadProject(sourcePath);\n return await project.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 { pac, project, review } from '@sdt-tools/core';\nimport { attachExplainFlag, runExplain } from '../util/ai-explain.js';\n\n/**\n * `sdt impact <fqn>` — single-FQN blast-radius answer. \"If I change\n * this, what breaks? What feeds it? What pending diagnostics\n * touch it?\" Composition of `@sdt-tools/core/lineage` (upstream/downstream)\n * and `@sdt-tools/core/diagnostics` (findings filtered to the FQN).\n *\n * Output is Markdown by default; `--format json` returns a structured\n * payload for CI integration.\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. ANALYTICS.GOLD.CUSTOMER).')\n .requiredOption('--source <path>', '.sdtproj or .sdtpac 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 Snowflake DBA 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) {\n if (sourcePath.endsWith('.sdtpac')) {\n const c = await pac.readPac(sourcePath);\n return c.model;\n }\n const loaded = await project.loadProject(sourcePath);\n return await project.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 * `sdt cost-estimate` — static heuristic estimator for the Snowflake\n * credits a migration script will consume when applied.\n *\n * Approach: classify each statement by its observable cost-class\n * (TABLE rebuild, CREATE OR REPLACE VIEW, ADD COLUMN, ALTER TYPE,\n * dynamic-table refresh, etc.) and assign a credit-band estimate per\n * class. Estimates are intentionally **ranges** rather than point\n * values because actual cost depends on row count, warehouse size,\n * and data layout — we don't pretend otherwise.\n *\n * The framing alone is uniquely valuable: no other Snowflake schema\n * tool surfaces \"this migration will roughly cost X credits at S\n * warehouse\" before you apply it.\n *\n * The classifier is regex-based and conservative — when a statement\n * doesn't match a known cost-class it's reported as\n * \"unknown / negligible\" so the user knows the estimate didn't see it.\n */\nexport function costEstimateCommand(): Command {\n const cmd = new Command('cost-estimate');\n cmd\n .description('Heuristic Snowflake-credit estimate for a generated migration script.')\n .requiredOption(\n '--script <path>',\n 'Path to a generated migration script (.sql) from `sdt publish --out`.',\n )\n .option(\n '--warehouse-size <size>',\n 'Target warehouse size for the cost ladder: XS | S | M | L | XL | 2XL | 3XL | 4XL.',\n 'S',\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 wh = String(opts.warehouseSize ?? 'S').toUpperCase() as WarehouseSize;\n const wantedSizes: readonly WarehouseSize[] = [\n 'XS',\n 'S',\n 'M',\n 'L',\n 'XL',\n '2XL',\n '3XL',\n '4XL',\n ];\n if (!wantedSizes.includes(wh)) {\n throw new Error(\n `Unknown --warehouse-size: ${wh}. Use one of ${wantedSizes.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\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 Snowflake cost engineer. Walk the team through this cost estimate: what is the dominant cost driver, what does the range mean in practice, and what knobs (warehouse size, 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 = 'XS' | 'S' | 'M' | 'L' | 'XL' | '2XL' | '3XL' | '4XL';\n\n/**\n * Snowflake's published credit-per-hour ladder, as of 2026-Q1.\n * XS = 1, S = 2, M = 4, L = 8, XL = 16, 2XL = 32, 3XL = 64, 4XL = 128.\n */\nconst CREDITS_PER_HOUR: Record<WarehouseSize, number> = {\n XS: 1,\n S: 2,\n M: 4,\n L: 8,\n XL: 16,\n '2XL': 32,\n '3XL': 64,\n '4XL': 128,\n};\n\ninterface CostClass {\n id: string;\n description: string;\n /** Conservative range estimate in **seconds of warehouse time**. */\n minSeconds: number;\n maxSeconds: number;\n /** Regex that matches the statement category. */\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: 'add-column',\n description: 'ALTER TABLE ADD COLUMN — metadata-only, no scan',\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',\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 (narrowing) — full data scan + rewrite',\n minSeconds: 30,\n maxSeconds: 600,\n test: (s) => /ALTER\\s+TABLE\\b.*\\bALTER\\s+COLUMN\\b.*\\bSET\\s+DATA\\s+TYPE\\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),\n },\n {\n id: 'create-mv',\n description: 'CREATE MATERIALIZED VIEW — initial population can be costly',\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-dynamic-table',\n description: 'CREATE DYNAMIC TABLE — initial materialisation cost',\n minSeconds: 60,\n maxSeconds: 1800,\n test: (s) => /CREATE\\s+(?:OR\\s+REPLACE\\s+)?DYNAMIC\\s+TABLE\\b/i.test(s),\n },\n {\n id: 'create-stream',\n description: 'CREATE STREAM — metadata-only',\n minSeconds: 1,\n maxSeconds: 3,\n test: (s) => /CREATE\\s+(?:OR\\s+REPLACE\\s+)?STREAM\\b/i.test(s),\n },\n {\n id: 'create-task',\n description: 'CREATE TASK — metadata-only',\n minSeconds: 1,\n maxSeconds: 3,\n test: (s) => /CREATE\\s+(?:OR\\s+REPLACE\\s+)?TASK\\b/i.test(s),\n },\n {\n id: 'create-warehouse',\n description: 'CREATE WAREHOUSE — metadata; cost depends on usage',\n minSeconds: 1,\n maxSeconds: 5,\n test: (s) => /CREATE\\s+(?:OR\\s+REPLACE\\s+)?WAREHOUSE\\b/i.test(s),\n },\n {\n id: 'pre-deploy-clone',\n description: 'CREATE DATABASE ... CLONE — Snowflake zero-copy clone (~instant)',\n minSeconds: 1,\n maxSeconds: 10,\n test: (s) => /CREATE\\s+(?:OR\\s+REPLACE\\s+)?DATABASE\\s+\\S+\\s+CLONE\\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 (-- … no DDL) — 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 creditsPerHour: 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 minCredits: number;\n maxCredits: 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 minCredits: number;\n maxCredits: number;\n };\n}\n\n/**\n * AI Phase 6 calibration — per-class empirical duration ranges harvested\n * from prior `QueryHistoryEntry[]` (typed in `@<tool>/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 /** Per-class empirical range; absent classes use the heuristic range. */\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 creditsPerHour = CREDITS_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 minCredits: (minSeconds / 3600) * creditsPerHour,\n maxCredits: (maxSeconds / 3600) * creditsPerHour,\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 minCredits: acc.minCredits + c.minCredits,\n maxCredits: acc.maxCredits + c.maxCredits,\n }),\n { minSeconds: 0, maxSeconds: 0, minCredits: 0, maxCredits: 0 },\n );\n return {\n warehouseSize,\n creditsPerHour,\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.creditsPerHour} credit/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.minCredits.toFixed(3)} – ${c.maxCredits.toFixed(3)} credit`,\n );\n }\n lines.push('');\n lines.push(\n ` TOTAL ≈ ${r.totals.minCredits.toFixed(3)} – ${r.totals.maxCredits.toFixed(3)} credit`,\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 cost depends on row counts, data layout,');\n lines.push(' and what other workloads share the warehouse. Treat the upper bound as a');\n lines.push(' 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.creditsPerHour} credit/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 | Credit range |');\n lines.push('|---|---|---|');\n for (const c of r.perClass) {\n lines.push(\n `| \\`${c.id}\\` (${c.description}) | ${c.count} | ${c.minCredits.toFixed(3)} – ${c.maxCredits.toFixed(3)} |`,\n );\n }\n lines.push('');\n lines.push(\n `**Total:** ${r.totals.minCredits.toFixed(3)} – ${r.totals.maxCredits.toFixed(3)} credit (${r.totals.minSeconds}–${r.totals.maxSeconds}s)`,\n );\n lines.push('');\n lines.push('> Ranges are heuristic. Actual cost depends on row counts and warehouse contention.');\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 type CompareSource,\n} from '@sdt-tools/core/compare';\nimport { safety } from '@sdt-tools/core';\nimport { pac, project, review } from '@sdt-tools/core';\nimport { attachExplainFlag, runExplain } from '../util/ai-explain.js';\nimport { attachRelatedOptions } from '../util/help-catalog.js';\n\n/**\n * `sdt pr-comment` — produce a Markdown PR sticky-comment from a\n * source↔target compare. Bundles the diff summary, reversibility-\n * grouped safety findings, project health diagnostics, and a\n * collapsible per-object changelog into a single deliverable a CI\n * step can POST as a pull-request comment.\n *\n * Distinct from `sdt review`: `review` is project-only, `pr-comment`\n * is change-driven (here's what's *in this PR*).\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>', '.sdtproj or .sdtpac (the desired state).')\n .requiredOption('--target <path>', '.sdtproj or .sdtpac (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('.sdtpac')\n ? new PacSource(sourcePath, 'source')\n : new ProjectSource(sourcePath, 'source');\n const tgt: CompareSource = targetPath.endsWith('.sdtpac')\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) {\n if (sourcePath.endsWith('.sdtpac')) {\n const c = await pac.readPac(sourcePath);\n return c.model;\n }\n const loaded = await project.loadProject(sourcePath);\n return await project.parseProjectModel(loaded);\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\n\n/**\n * `sdt template <kind> <name>` — schema cookbook generator. Produces\n * a complete set of `.sql` files implementing a common pattern, ready\n * to drop into a `.sdtproj`'s object tree. Saves a junior engineer\n * from re-inventing the SCD2 pattern from scratch.\n *\n * Supported kinds:\n * - `scd1` — Slowly-changing-dimension type-1 (overwrite, no history).\n * - `scd2` — Slowly-changing-dimension type-2 (history-preserving).\n * - `scd3` — Slowly-changing-dimension type-3 (one previous value).\n * - `scd4` — Slowly-changing-dimension type-4 (current + history table).\n * - `scd6` — Hybrid 1+2+3 (current + valid_from/to + previous value).\n * - `star` — Star schema fact + N dimensions.\n * - `fact` — Fact table only, with surrogate-key FKs to named dims.\n * - `scd2-merge` — Canonical MERGE statement to load an SCD2 dimension.\n * - `current-view` — `CREATE VIEW` over an SCD2 table where IS_CURRENT = TRUE.\n * - `time-series` — Hash-partitioned time-series with retention.\n * - `audit` — Generic audit-log table with append-only constraints.\n *\n * Mirrors `ddt template`. Patterns are conservative: every template\n * sets a PK, populates COMMENT fields, and prefers `CREATE OR ALTER`\n * over `CREATE OR REPLACE` to play well with the safety classifier.\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('--db <database>', 'Database name. Default DEMO_DB.', 'DEMO_DB')\n .option('--schema <schema>', 'Schema name. Default PUBLIC.', 'PUBLIC')\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 DEMO_DB.PUBLIC.<name>_STAGE.',\n )\n .option('--retention-days <n>', '[time-series] Retention window in days. Default 90.', '90')\n .option(\n '--hybrid',\n 'Emit CREATE HYBRID TABLE (Unistore row-store) instead of CREATE OR ALTER TABLE. Constraints become enforced; CLUSTER BY is suppressed (not supported on Hybrid Tables).',\n )\n .action(async (kindArg, nameArg, opts) => {\n const kind = String(kindArg).toLowerCase();\n const name = String(nameArg);\n const db = String(opts.db);\n const schema = String(opts.schema);\n const hybrid = Boolean(opts.hybrid);\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 if (hybrid && (kind === 'scd2-merge' || kind === 'current-view')) {\n console.error(`Warning: --hybrid has no effect on ${kind} (no table DDL emitted).`);\n }\n\n const ctx = { db, schema, name, hybrid };\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) : `${db}.${schema}.${name.toUpperCase()}_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 db: string;\n schema: string;\n name: string;\n /** When true, emit CREATE HYBRID TABLE with enforced constraints and no CLUSTER BY. */\n hybrid?: boolean;\n}\n\nfunction header(why: string): string {\n return `-- Generated by \\`sdt template\\`. Why this pattern is the right shape:\\n-- ${why}\\n--\\n-- Edit freely; this is just a starting point.\\n\\n`;\n}\n\n/** DDL verb for table creation — Hybrid Tables can't use CREATE OR ALTER. */\nfunction tableKw(c: Ctx, tableName: string): string {\n return c.hybrid\n ? `CREATE HYBRID TABLE ${c.db}.${c.schema}.${tableName}`\n : `CREATE OR ALTER TABLE ${c.db}.${c.schema}.${tableName}`;\n}\n\n/** Primary-key constraint. Hybrid Tables enforce PKs, regular tables don't. */\nfunction pkConstraint(name: string, cols: string, c: Ctx): string {\n return c.hybrid\n ? `CONSTRAINT ${name} PRIMARY KEY (${cols})`\n : `CONSTRAINT ${name} PRIMARY KEY (${cols}) NOT ENFORCED`;\n}\n\n/** Unique constraint. Hybrid Tables enforce UKs, regular tables don't. */\nfunction ukConstraint(name: string, cols: string, c: Ctx): string {\n return c.hybrid\n ? `CONSTRAINT ${name} UNIQUE (${cols})`\n : `CONSTRAINT ${name} UNIQUE (${cols}) NOT ENFORCED`;\n}\n\n/** CLUSTER BY clause — suppressed on Hybrid Tables (not supported). */\nfunction clusterBy(expr: string, c: Ctx): string {\n return c.hybrid ? '' : `\\nCLUSTER BY (${expr})`;\n}\n\nfunction renderScd1(c: Ctx): Record<string, string> {\n const upper = c.name.toUpperCase();\n return {\n [`${c.db}/${c.schema}/Tables/${upper}.sql`]:\n header(\n `SCD1 overwrites the row in place when an attribute changes. No history is\n-- preserved. Use this when downstream consumers only care about the *current*\n-- state and the dimension is small enough that losing history is fine.\n-- LOAD_TS/UPDATED_TS give you minimal auditability without history-table cost.`,\n ) +\n `${tableKw(c, upper)} (\n ${upper}_SK NUMBER(38,0) NOT NULL AUTOINCREMENT COMMENT 'Surrogate key — stable across overwrites',\n ${upper}_BK VARCHAR NOT NULL COMMENT 'Business key',\n ATTRIBUTE_1 VARCHAR COMMENT 'Replace with real columns',\n ATTRIBUTE_2 VARCHAR COMMENT 'Replace with real columns',\n LOAD_TS TIMESTAMP_NTZ NOT NULL DEFAULT CURRENT_TIMESTAMP() COMMENT 'When the row was first inserted',\n UPDATED_TS TIMESTAMP_NTZ COMMENT 'When the row was last overwritten',\n ${pkConstraint(`PK_${upper}`, `${upper}_SK`, c)},\n ${ukConstraint(`UK_${upper}_BK`, `${upper}_BK`, c)}\n)\nCOMMENT = 'SCD1 dimension — overwrite-on-change. No history kept; join on ${upper}_BK.';\n`,\n };\n}\n\nfunction renderScd2(c: Ctx): Record<string, string> {\n const upper = c.name.toUpperCase();\n return {\n [`${c.db}/${c.schema}/Tables/${upper}.sql`]:\n header(\n `SCD2 preserves every historical version of a row by closing the previous row's\n-- VALID_TO when the natural key reappears with new attribute values. Use this\n-- when downstream analytics needs \"what did this row look like on date X\".`,\n ) +\n `${tableKw(c, upper)} (\n ${upper}_SK NUMBER(38,0) NOT NULL AUTOINCREMENT COMMENT 'Surrogate key — unique per version',\n ${upper}_BK VARCHAR NOT NULL COMMENT 'Business key — stable across versions',\n ATTRIBUTE_1 VARCHAR COMMENT 'Replace with real columns',\n ATTRIBUTE_2 VARCHAR COMMENT 'Replace with real columns',\n VALID_FROM TIMESTAMP_NTZ NOT NULL COMMENT 'When this version became current',\n VALID_TO TIMESTAMP_NTZ 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_NTZ NOT NULL DEFAULT CURRENT_TIMESTAMP() COMMENT 'Insertion timestamp',\n ${pkConstraint(`PK_${upper}`, `${upper}_SK`, c)}\n)\nCOMMENT = 'SCD2 dimension — preserves history. Treat business key + IS_CURRENT as the natural join target.';\n`,\n [`${c.db}/${c.schema}/Streams/${upper}_STREAM.sql`]:\n header(\n `Stream over the SCD2 table lets downstream tasks consume only the rows that\n-- changed since they last read. Drop this if you don't have a downstream\n-- consumer that needs incremental updates.`,\n ) +\n `CREATE OR ALTER STREAM ${c.db}.${c.schema}.${upper}_STREAM ON TABLE ${c.db}.${c.schema}.${upper}\nCOMMENT = 'CDC stream over ${upper}. Read by downstream tasks for incremental processing.';\n`,\n };\n}\n\nfunction renderScd3(c: Ctx, tracked: string[]): Record<string, string> {\n const upper = c.name.toUpperCase();\n const cols = (tracked.length ? tracked : ['attribute_1']).map((t) => t.toUpperCase());\n const prevCols = cols\n .map(\n (t) =>\n ` PREV_${t} VARCHAR COMMENT 'Prior value of ${t}, captured on overwrite'`,\n )\n .join(',\\n');\n return {\n [`${c.db}/${c.schema}/Tables/${upper}.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 `${tableKw(c, upper)} (\n ${upper}_SK NUMBER(38,0) NOT NULL AUTOINCREMENT COMMENT 'Surrogate key',\n ${upper}_BK VARCHAR NOT NULL COMMENT 'Business key',\n${cols.map((t) => ` ${t} VARCHAR COMMENT 'Current value'`).join(',\\n')},\n${prevCols},\n PREV_CHANGED_TS TIMESTAMP_NTZ COMMENT 'When prior values were captured',\n LOAD_TS TIMESTAMP_NTZ NOT NULL DEFAULT CURRENT_TIMESTAMP() COMMENT 'Insertion timestamp',\n UPDATED_TS TIMESTAMP_NTZ COMMENT 'When this row was last overwritten',\n ${pkConstraint(`PK_${upper}`, `${upper}_SK`, c)},\n ${ukConstraint(`UK_${upper}_BK`, `${upper}_BK`, c)}\n)\nCOMMENT = 'SCD3 dimension — current + one prior value for ${cols.join(', ')}.';\n`,\n };\n}\n\nfunction renderScd4(c: Ctx): Record<string, string> {\n const upper = c.name.toUpperCase();\n return {\n [`${c.db}/${c.schema}/Tables/${upper}.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 the current-state lookups are hot\n-- (every fact query joins to it) and you want to keep that join skinny.`,\n ) +\n `${tableKw(c, upper)} (\n ${upper}_SK NUMBER(38,0) NOT NULL AUTOINCREMENT COMMENT 'Surrogate key',\n ${upper}_BK VARCHAR NOT NULL COMMENT 'Business key',\n ATTRIBUTE_1 VARCHAR COMMENT 'Replace with real columns',\n ATTRIBUTE_2 VARCHAR COMMENT 'Replace with real columns',\n LOAD_TS TIMESTAMP_NTZ NOT NULL DEFAULT CURRENT_TIMESTAMP() COMMENT 'When the row was inserted',\n UPDATED_TS TIMESTAMP_NTZ COMMENT 'When the row was last overwritten',\n ${pkConstraint(`PK_${upper}`, `${upper}_SK`, c)},\n ${ukConstraint(`UK_${upper}_BK`, `${upper}_BK`, c)}\n)\nCOMMENT = 'SCD4 current-state table. Pair with ${upper}_HISTORY for change tracking.';\n`,\n [`${c.db}/${c.schema}/Tables/${upper}_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 `${tableKw(c, `${upper}_HISTORY`)} (\n ${upper}_HISTORY_SK NUMBER(38,0) NOT NULL AUTOINCREMENT COMMENT 'Surrogate id for each historical snapshot',\n ${upper}_BK VARCHAR NOT NULL COMMENT 'Business key',\n ATTRIBUTE_1 VARCHAR COMMENT 'Snapshot of column at CHANGED_TS',\n ATTRIBUTE_2 VARCHAR COMMENT 'Snapshot of column at CHANGED_TS',\n CHANGED_TS TIMESTAMP_NTZ NOT NULL COMMENT 'When this snapshot was taken',\n LOAD_TS TIMESTAMP_NTZ NOT NULL DEFAULT CURRENT_TIMESTAMP() COMMENT 'When the row was appended',\n ${pkConstraint(`PK_${upper}_HISTORY`, `${upper}_HISTORY_SK`, c)}\n)${clusterBy(`${upper}_BK, CHANGED_TS`, c)}\nCOMMENT = 'SCD4 history-side. Append-only snapshots of ${upper}; reconstruct as-of state via window functions.';\n`,\n };\n}\n\nfunction renderScd6(c: Ctx, tracked: string[]): Record<string, string> {\n const upper = c.name.toUpperCase();\n const cols = (tracked.length ? tracked : ['attribute_1']).map((t) => t.toUpperCase());\n const prevCols = cols\n .map(\n (t) =>\n ` PREV_${t} VARCHAR COMMENT 'Prior value of ${t}'`,\n )\n .join(',\\n');\n return {\n [`${c.db}/${c.schema}/Tables/${upper}.sql`]:\n header(\n `SCD6 = 1 + 2 + 3 hybrid. You get full SCD2 history (rows per version),\n-- SCD3 \"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 `${tableKw(c, upper)} (\n ${upper}_SK NUMBER(38,0) NOT NULL AUTOINCREMENT COMMENT 'Surrogate key — unique per version',\n ${upper}_BK VARCHAR NOT NULL COMMENT 'Business key — stable across versions',\n${cols.map((t) => ` ${t} VARCHAR COMMENT 'Value on THIS version'`).join(',\\n')},\n${cols.map((t) => ` CURRENT_${t} VARCHAR COMMENT 'Current value for the BK (SCD1 denorm)'`).join(',\\n')},\n${prevCols},\n VALID_FROM TIMESTAMP_NTZ NOT NULL COMMENT 'When this version became current',\n VALID_TO TIMESTAMP_NTZ 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_NTZ NOT NULL DEFAULT CURRENT_TIMESTAMP() COMMENT 'Insertion timestamp',\n ${pkConstraint(`PK_${upper}`, `${upper}_SK`, c)}\n)\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.toUpperCase();\n const out: Record<string, string> = {};\n for (const d of dims) {\n const upper = d.toUpperCase();\n out[`${c.db}/${c.schema}/Tables/DIM_${upper}.sql`] =\n header(`Dimension table — describes the WHAT. Joined by the fact via DIM_${upper}_SK.`) +\n `${tableKw(c, `DIM_${upper}`)} (\n DIM_${upper}_SK NUMBER(38,0) NOT NULL AUTOINCREMENT COMMENT 'Surrogate key',\n ${upper}_BK VARCHAR NOT NULL COMMENT 'Business key',\n ${upper}_NAME VARCHAR COMMENT 'Replace with real attributes',\n COUNTRY VARCHAR COMMENT 'Example attribute',\n ${pkConstraint(`PK_DIM_${upper}`, `DIM_${upper}_SK`, c)}\n)\nCOMMENT = 'Dimension table for the ${fact} star schema.';\n`;\n }\n out[`${c.db}/${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 ) +\n `${tableKw(c, `FACT_${fact}`)} (\n FACT_${fact}_SK NUMBER(38,0) NOT NULL AUTOINCREMENT COMMENT 'Surrogate key',\n${dims.map((d) => ` DIM_${d.toUpperCase()}_SK NUMBER(38,0) COMMENT 'FK to DIM_${d.toUpperCase()}'`).join(',\\n')},\n EVENT_TS TIMESTAMP_NTZ NOT NULL COMMENT 'When the event occurred',\n MEASURE_AMOUNT NUMBER(38,4) COMMENT 'Primary measure — replace with real columns',\n MEASURE_QUANTITY NUMBER(38,0) COMMENT 'Secondary measure',\n LOAD_TS TIMESTAMP_NTZ NOT NULL DEFAULT CURRENT_TIMESTAMP() COMMENT 'Insertion timestamp',\n ${pkConstraint(`PK_FACT_${fact}`, `FACT_${fact}_SK`, c)}\n)${clusterBy('EVENT_TS', c)}\nCOMMENT = 'Fact table for the ${fact} star. CLUSTER BY date keeps recent-event scans cheap.';\n`;\n return out;\n}\n\nfunction renderFact(c: Ctx, dims: string[]): Record<string, string> {\n const fact = c.name.toUpperCase();\n return {\n [`${c.db}/${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. Surrogate-key FKs follow the DIM_<NAME>_SK convention.`,\n ) +\n `${tableKw(c, `FACT_${fact}`)} (\n FACT_${fact}_SK NUMBER(38,0) NOT NULL AUTOINCREMENT COMMENT 'Surrogate key',\n${dims.map((d) => ` DIM_${d.toUpperCase()}_SK NUMBER(38,0) COMMENT 'FK to DIM_${d.toUpperCase()}'`).join(',\\n')},\n EVENT_TS TIMESTAMP_NTZ NOT NULL COMMENT 'When the event occurred',\n MEASURE_AMOUNT NUMBER(38,4) COMMENT 'Primary measure — replace with real columns',\n MEASURE_QUANTITY NUMBER(38,0) COMMENT 'Secondary measure',\n LOAD_TS TIMESTAMP_NTZ NOT NULL DEFAULT CURRENT_TIMESTAMP() COMMENT 'Insertion timestamp',\n ${pkConstraint(`PK_FACT_${fact}`, `FACT_${fact}_SK`, c)}\n)${clusterBy('EVENT_TS', c)}\nCOMMENT = 'Fact table FACT_${fact}. Add this to an existing star — dimensions assumed to exist.';\n`,\n };\n}\n\nfunction renderScd2Merge(c: Ctx, source: string): Record<string, string> {\n const upper = c.name.toUpperCase();\n return {\n [`${c.db}/${c.schema}/Scripts/MERGE_${upper}.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. Wrap both in a transaction so you don't end up with two current\n-- rows. Source: ${source}.`,\n ) +\n `-- Step 1 — close the previous version when attributes change for an existing BK.\nBEGIN TRANSACTION;\n\nMERGE INTO ${c.db}.${c.schema}.${upper} AS tgt\nUSING (\n SELECT\n src.${upper}_BK,\n src.ATTRIBUTE_1,\n src.ATTRIBUTE_2\n FROM ${source} AS src\n) AS src\nON tgt.${upper}_BK = src.${upper}_BK\n AND tgt.IS_CURRENT = TRUE\nWHEN MATCHED\n AND (tgt.ATTRIBUTE_1 IS DISTINCT FROM src.ATTRIBUTE_1\n OR tgt.ATTRIBUTE_2 IS DISTINCT FROM src.ATTRIBUTE_2)\n THEN UPDATE SET\n VALID_TO = CURRENT_TIMESTAMP(),\n IS_CURRENT = FALSE;\n\n-- Step 2 — insert the new version for changed BKs + brand-new BKs.\nINSERT INTO ${c.db}.${c.schema}.${upper} (\n ${upper}_BK, ATTRIBUTE_1, ATTRIBUTE_2,\n VALID_FROM, VALID_TO, IS_CURRENT\n)\nSELECT\n src.${upper}_BK,\n src.ATTRIBUTE_1,\n src.ATTRIBUTE_2,\n CURRENT_TIMESTAMP(),\n NULL,\n TRUE\nFROM ${source} AS src\nLEFT JOIN ${c.db}.${c.schema}.${upper} AS tgt\n ON tgt.${upper}_BK = src.${upper}_BK\n AND tgt.IS_CURRENT = TRUE\nWHERE tgt.${upper}_BK IS NULL\n OR (tgt.ATTRIBUTE_1 IS DISTINCT FROM src.ATTRIBUTE_1\n OR tgt.ATTRIBUTE_2 IS DISTINCT FROM src.ATTRIBUTE_2);\n\nCOMMIT;\n`,\n };\n}\n\nfunction renderCurrentView(c: Ctx): Record<string, string> {\n const upper = c.name.toUpperCase();\n return {\n [`${c.db}/${c.schema}/Views/V_${upper}_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 — Snowflake filter-pushdown handles it.`,\n ) +\n `CREATE OR REPLACE VIEW ${c.db}.${c.schema}.V_${upper}_CURRENT\nCOMMENT = 'Current rows from ${upper} (SCD2). Join here instead of filtering IS_CURRENT manually.'\nAS\nSELECT *\nFROM ${c.db}.${c.schema}.${upper}\nWHERE IS_CURRENT = TRUE;\n`,\n };\n}\n\nfunction renderTimeSeries(c: Ctx, retentionDays: number): Record<string, string> {\n const upper = c.name.toUpperCase();\n return {\n [`${c.db}/${c.schema}/Tables/${upper}.sql`]:\n header(\n `Time-series table — append-only, clustered by event timestamp so recent-event\n-- scans prune to a small number of micropartitions. DATA_RETENTION_TIME_IN_DAYS\n-- bounds Time Travel cost; aged-out rows must be archived elsewhere.`,\n ) +\n `${tableKw(c, upper)} (\n EVENT_ID NUMBER(38,0) NOT NULL AUTOINCREMENT COMMENT 'Surrogate id',\n EVENT_TS TIMESTAMP_NTZ NOT NULL COMMENT 'When the event occurred',\n EVENT_TYPE VARCHAR COMMENT 'Discriminator — index of partition by event_type if useful',\n ENTITY_ID VARCHAR COMMENT 'Foreign key to the entity the event is about',\n PAYLOAD VARIANT COMMENT 'Event-specific payload (semistructured)',\n INGESTED_TS TIMESTAMP_NTZ NOT NULL DEFAULT CURRENT_TIMESTAMP() COMMENT 'When SDT loaded the row',\n ${pkConstraint(`PK_${upper}`, 'EVENT_ID', c)}\n)${clusterBy('EVENT_TS', c)}\nDATA_RETENTION_TIME_IN_DAYS = ${Math.max(1, Math.min(retentionDays, 90))}\nCOMMENT = 'Time-series ${upper}. Aged out beyond DATA_RETENTION_TIME_IN_DAYS; archive separately if you need longer history.';\n`,\n };\n}\n\nfunction renderAudit(c: Ctx): Record<string, string> {\n const upper = c.name.toUpperCase();\n return {\n [`${c.db}/${c.schema}/Tables/${upper}_AUDIT.sql`]:\n header(\n `Audit log — append-only by convention. INSERT-only INSERT-only permissions on\n-- downstream roles enforce the \"append-only\" property; this table itself doesn't\n-- block updates, but the role grants do. Pair with a row-access policy if\n-- stronger guarantees are needed.`,\n ) +\n `${tableKw(c, `${upper}_AUDIT`)} (\n AUDIT_ID NUMBER(38,0) NOT NULL AUTOINCREMENT COMMENT 'Surrogate id',\n AUDIT_TS TIMESTAMP_NTZ NOT NULL DEFAULT CURRENT_TIMESTAMP() COMMENT 'When the event was logged',\n ACTOR VARCHAR NOT NULL COMMENT 'Who performed the action (user / service-account)',\n ACTION VARCHAR NOT NULL COMMENT 'What happened (e.g. CREATE_USER, ROLE_GRANT)',\n TARGET VARCHAR COMMENT 'What it was performed on',\n DETAILS VARIANT COMMENT 'Free-form payload — keep it small',\n ${pkConstraint(`PK_${upper}_AUDIT`, 'AUDIT_ID', c)}\n)\nCOMMENT = 'Audit log for ${upper}. 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 { pac, project } from '@sdt-tools/core';\nimport type { SnowflakeObject } from '@sdt-tools/core/model';\n\n/**\n * `sdt anonymize` — generate masking-policy DDL for PII columns\n * discovered in a project model. Pairs with the L012 `pii-without-mask`\n * lint rule: the lint surfaces *which* columns need masking; this\n * command writes the policy DDL ready to copy into the project.\n *\n * Use case: refresh prod → dev pipeline. Most teams need to\n * pseudonymize PII before any non-prod role sees the data. This\n * command auto-generates a starter set of MASKING POLICY statements\n * + the ALTER TABLE ... ALTER COLUMN ... SET MASKING POLICY calls\n * to apply them.\n *\n * Output is intentionally **conservative**: every emitted policy has\n * `RETURN VAL` (no-op) when the current role is in `('PROD_ETL')` so\n * production keeps working as-is; every other role sees a hashed /\n * redacted value. Adjust the role allow-list before applying.\n */\nexport function anonymizeCommand(): Command {\n const cmd = new Command('anonymize');\n cmd\n .description('Generate MASKING POLICY DDL for PII columns detected in the project model.')\n .requiredOption('--source <path>', '.sdtproj or .sdtpac to analyze.')\n .option(\n '--unmasked-role <name>',\n \"Role the unmasked value is visible to. Default 'PROD_ETL'.\",\n 'PROD_ETL',\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 unmaskedRole = String(opts.unmaskedRole);\n const candidates = collectPiiColumns(model);\n if (candidates.length === 0) {\n console.error(\n 'No PII columns detected (heuristic on column names: email, phone, ssn, dob, …).',\n );\n console.error(\n 'If the schema has PII you know about, add a MASKING POLICY by hand and re-run lint to confirm.',\n );\n return;\n }\n const sql = renderAnonymizeSql(candidates, unmaskedRole);\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 role allow-list (`unmaskedRole`) before applying. Default fully hides values from every role except the one passed in.',\n );\n });\n return cmd;\n}\n\ninterface PiiColumn {\n fqn: string;\n column: string;\n category: 'email' | 'phone' | 'name' | 'dob' | 'ssn' | 'address' | 'credit-card' | 'generic';\n}\n\n/**\n * Heuristic PII detector — matches column names against a curated\n * list of likely PII patterns. Same patterns the L012 lint rule\n * uses. We pick the masking strategy from the category.\n */\nfunction collectPiiColumns(model: readonly SnowflakeObject[]): PiiColumn[] {\n const out: PiiColumn[] = [];\n for (const o of model) {\n if (o.objectType !== '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 fqn = [o.fqn.database, o.fqn.schema, o.fqn.name].filter(Boolean).join('.');\n for (const c of cols) {\n const category = classify(c.name);\n if (category) out.push({ fqn, 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(cols: PiiColumn[], unmaskedRole: string): string {\n const lines: string[] = [];\n lines.push(`-- Generated by \\`sdt anonymize\\`.`);\n lines.push(\n `-- Edit the role allow-list before applying. Default: only ${unmaskedRole} sees unmasked values.`,\n );\n lines.push('');\n // One reusable policy per category; the policies belong in a shared schema.\n const categoriesNeeded = new Set(cols.map((c) => c.category));\n for (const cat of categoriesNeeded) {\n lines.push(`-- Masking policy for ${cat} columns`);\n lines.push(\n `CREATE OR ALTER MASKING POLICY MASK_${cat.toUpperCase().replace(/-/g, '_')} AS (val STRING) RETURNS STRING ->`,\n );\n lines.push(` CASE`);\n lines.push(` WHEN CURRENT_ROLE() IN ('${unmaskedRole}') THEN val`);\n lines.push(` ELSE ${maskExpression(cat)}`);\n lines.push(` END;`);\n lines.push('');\n }\n lines.push('-- Apply policies to columns');\n for (const c of cols) {\n lines.push(\n `ALTER TABLE ${c.fqn} MODIFY COLUMN ${c.column} SET MASKING POLICY MASK_${c.category.toUpperCase().replace(/-/g, '_')};`,\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 `'***-***-' || RIGHT(val, 4)`;\n case 'ssn':\n return `'***-**-' || RIGHT(val, 4)`;\n case 'credit-card':\n return `'****-****-****-' || RIGHT(val, 4)`;\n case 'dob':\n return `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) {\n if (sourcePath.endsWith('.sdtpac')) {\n const c = await pac.readPac(sourcePath);\n return c.model;\n }\n const loaded = await project.loadProject(sourcePath);\n return await project.parseProjectModel(loaded);\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { project, testFramework } from '@sdt-tools/core';\nimport { getProfile, SnowflakeConnection } from '@sdt-tools/core/connection';\nimport { logger } from '../util/logger.js';\n\n/**\n * `sdt test` — declarative test framework. Author tests in YAML\n * alongside DDL; `sdt test render` compiles them to SQL assertions;\n * `sdt test list` enumerates them.\n *\n * dbt-test parity. Free tier — every team can author tests and run\n * them in CI without a license.\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 .sdtproj file.')\n .action(async (opts) => {\n const loaded = await project.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/<db>/<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 account contact.')\n .requiredOption('-p, --project <path>', 'Path to the .sdtproj file.')\n .option('-o, --out <path>', 'Write to file. Defaults to stdout.')\n .action(async (opts) => {\n const loaded = await project.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 Snowflake account 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 .sdtproj 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. \"mydb.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 .sdt/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 project.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/<db>/<schema>/<table>.test.yaml.',\n );\n return;\n }\n const profile = await getProfile(String(opts.connection));\n const conn = new SnowflakeConnection(profile);\n logger.step(`test run: connecting to ${profile.account} as ${profile.auth.username}…`);\n await conn.connect();\n const snapshotsDir = path.join(loaded.rootDir, '.sdt', '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 logger.info(\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 account contact. Emits a Markdown table (default) or JSON.',\n )\n .requiredOption('-p, --project <path>', 'Path to the .sdtproj 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 project.loadProject(String(opts.project));\n const files = await testFramework.discoverTests(loaded.rootDir);\n const model = await project.parseProjectModel(loaded);\n const testable = new Set<string>([\n 'TABLE',\n 'EXTERNAL_TABLE',\n 'ICEBERG_TABLE',\n 'HYBRID_TABLE',\n 'DYNAMIC_TABLE',\n 'EVENT_TABLE',\n 'VIEW',\n 'MATERIALIZED_VIEW',\n ]);\n const fqns: string[] = [];\n for (const obj of model) {\n if (!testable.has(obj.objectType)) continue;\n const db = obj.fqn.database;\n const sc = obj.fqn.schema;\n if (!db || !sc) continue;\n fqns.push(`${db}.${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 logger.info(\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 { getProfile, SnowflakeConnection } from '@sdt-tools/core/connection';\n\n/**\n * `sdt branch` — PlanetScale-style branching for Snowflake. A branch\n * is a Snowflake **zero-copy clone** of a base database — instant to\n * create, free until you start writing to it, and disposable when\n * you're done. The deploy-request workflow becomes:\n *\n * sdt branch create feature-x --from PROD_DB\n * # … iterate against feature-x using sdt publish --apply …\n * sdt compare … (preview the diff between the branch and PROD)\n * sdt branch drop feature-x\n *\n * No competing Snowflake schema tool has this. Atlas + Liquibase\n * lack the zero-copy substrate; Bytebase tries to fit a generic\n * branching workflow on top of generic SQL.\n *\n * Subcommands:\n * create <name> --from <db> [--connection <profile>]\n * drop <name> [--connection <profile>]\n * list --connection <profile>\n *\n * `--connection` makes the command live; without it the SQL is\n * emitted to stdout for the user to run manually.\n */\nexport function branchCommand(): Command {\n const cmd = new Command('branch').description(\n 'PlanetScale-style branching via Snowflake zero-copy clone. create / drop / list.',\n );\n\n cmd\n .command('create <name>')\n .description('Create a zero-copy clone of <from-database> named <name>.')\n .requiredOption('--from <database>', 'Base database to clone.')\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 the generated SQL to a file. Defaults to stdout when --connection is omitted.',\n )\n .action(async (name, opts) => {\n const branchDb = String(name);\n const fromDb = String(opts.from);\n const sql = `-- Branch ${branchDb} = zero-copy clone of ${fromDb}\\nCREATE OR REPLACE DATABASE ${branchDb} CLONE ${fromDb};\\n`;\n await runOrEmit(sql, opts);\n });\n\n cmd\n .command('drop <name>')\n .description('Drop a branch database. Irreversible.')\n .option(\n '--connection <profile>',\n 'Connection profile to execute against. Omit to emit SQL only.',\n )\n .option('-o, --out <path>', 'Write the generated SQL to a file. Defaults to stdout.')\n .action(async (name, opts) => {\n const sql = `-- Drop branch ${name}\\nDROP DATABASE IF EXISTS ${name};\\n`;\n await runOrEmit(sql, opts);\n });\n\n cmd\n .command('list')\n .description('List branches (databases whose names suggest a branch).')\n .requiredOption('--connection <profile>', 'Connection profile to query.')\n .option('--pattern <like>', 'SHOW DATABASES LIKE pattern. Defaults to all databases.', '%')\n .action(async (opts) => {\n const profile = await getProfile(String(opts.connection));\n const conn = new SnowflakeConnection(profile);\n try {\n await conn.connect();\n const rows = await conn.query(\n `SHOW DATABASES LIKE '${String(opts.pattern).replace(/'/g, \"''\")}'`,\n );\n const list = Array.isArray(rows) ? rows : [];\n for (const r of list) {\n const rec = r as Record<string, unknown>;\n const name = rec.name ?? rec.NAME;\n const origin = rec.origin ?? rec.ORIGIN ?? '';\n if (!name) continue;\n console.log(` ${String(name).padEnd(40)} ${origin ? `origin=${origin}` : ''}`);\n }\n console.log('');\n console.log(`${list.length} database(s) found.`);\n } finally {\n await conn.disconnect();\n }\n });\n\n return cmd;\n}\n\nasync function runOrEmit(\n sql: string,\n opts: { connection?: unknown; out?: unknown },\n): Promise<void> {\n if (opts.connection) {\n const profile = await getProfile(String(opts.connection));\n const conn = new SnowflakeConnection(profile);\n try {\n await conn.connect();\n for (const stmt of sql\n .split(';')\n .map((s) => s.trim())\n .filter(Boolean)) {\n if (stmt.startsWith('--')) continue;\n console.error(`> ${stmt.split('\\n')[0]}`);\n await conn.query(stmt);\n }\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 return;\n }\n process.stdout.write(sql);\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { interop, pac, project, schema, validate as validateNs } from '@sdt-tools/core';\n\n/**\n * `sdt schema` — interop with third-party schema-modeling formats.\n *\n * **What this is**: a thin import/export bridge between `.sdtproj`\n * and well-known interchange formats (DBML, draw.io XML). It exists\n * so users coming from `dbdiagram.io`, draw.io, or other modelers\n * can drop their work into SDT — and vice versa.\n *\n * **What this is NOT**: erwin Data Modeler, ER/Studio, DbSchema, or\n * Hackolade. We do not contain or redistribute any code from those\n * products. See root `NOTICE` for the interop attribution and the\n * \"what this product is NOT\" statement.\n *\n * Subcommands:\n * - `import-dbml <file>` — read a DBML file, emit `.sql` files\n * into <out>/.\n * - `export-dbml --source <pac|proj>` — emit DBML text from a\n * project model.\n * - `export-drawio --source <pac|proj>` — emit a `.drawio` XML\n * file ready to open in any diagrams.net editor.\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 — SDT remains the canonical model.',\n );\n\n cmd\n .command('import-dbml <file>')\n .description('Import a DBML file and emit Snowflake 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, 'DEMO_DB', 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(`Database name defaulted to DEMO_DB; rename the top-level folder if needed.`);\n console.error(\n `Inferred refs (${doc.refs.length}) were preserved as inline comments — review and add FOREIGN KEY constraints by hand.`,\n );\n });\n\n cmd\n .command('export-dbml')\n .description(\n 'Emit DBML text from a project model. Lossy projection — Snowflake-specific features are emitted as comments.',\n )\n .requiredOption('--source <path>', '.sdtproj or .sdtpac 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>', '.sdtproj or .sdtpac 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 (Phase A of the interop wave) ───\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>', '.sdtproj or .sdtpac 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>', '.sdtproj or .sdtpac containing the star.')\n .requiredOption('--root <fqn>', 'Fully-qualified fact-table FQN (database.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 // Non-zero exit when the fact wasn't found or there are issues — CI-gateable.\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>', '.sdtproj or .sdtpac containing the star.')\n .requiredOption('--root <fqn>', 'Fully-qualified fact-table FQN (database.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 Snowflake CREATE TABLE with heuristic type inference. Review before deploy.',\n )\n .requiredOption(\n '--name <fqn>',\n 'Fully-qualified table name (database.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('-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, { fqn, orReplace: !!opts.orReplace });\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 VARCHAR. 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 Snowflake CREATE TABLE. No data is read — only the schema header.\",\n )\n .requiredOption(\n '--name <fqn>',\n 'Fully-qualified table name (database.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('-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, { fqn, orReplace: !!opts.orReplace });\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(\n 'Import a dbt-generated manifest.json (or catalog.json); each model/seed/source becomes a table.',\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.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 db = t.database ?? 'DEMO_DB';\n const sch = t.schema ?? 'PUBLIC';\n const dir = path.join(outDir, db, 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 if (c.primaryKey) mods.push('PRIMARY KEY');\n return ` ${c.name.padEnd(28)} ${snowflakeType(c.dataType)}${mods.length > 0 ? ' ' + mods.join(' ') : ''}${c.comment ? ` COMMENT '${c.comment.replace(/'/g, \"''\")}'` : ''}`;\n })\n .join(',\\n');\n const ddl = `-- Imported by \\`sdt schema import-*\\` from source: ${result.source}.\\n-- Review and refine; SDT is the canonical model from here on.\\n\\nCREATE OR ALTER TABLE ${db}.${sch}.${t.name} (\\n${colDdl}\\n)${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 snowflakeType(dbmlType: string): string {\n const t = dbmlType.toLowerCase().trim();\n if (t === 'int' || t === 'integer' || t === 'serial') return 'NUMBER(38,0)';\n if (t === 'bigint') return 'NUMBER(38,0)';\n if (t === 'smallint') return 'NUMBER(5,0)';\n if (t === 'decimal' || t === 'numeric') return 'NUMBER(38,9)';\n if (t === 'float' || t === 'double') return 'FLOAT';\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_NTZ';\n if (t === 'time') return 'TIME';\n if (t.startsWith('varchar') || t.startsWith('number')) return dbmlType.toUpperCase();\n if (t === 'text' || t === 'string') return 'VARCHAR';\n if (t === 'json' || t === 'jsonb' || t === 'variant') return 'VARIANT';\n if (t === 'array') return 'ARRAY';\n if (t === 'uuid') return 'VARCHAR(36)';\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 \\`sdt schema import-dbml\\`.`);\n lines.push(`-- Review and refine; SDT 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 if (c.pk) mods.push('PRIMARY KEY');\n return ` ${c.name.padEnd(28)} ${snowflakeType(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 (review before adding as FOREIGN KEY constraints):`);\n for (const r of tableRefs) lines.push(`-- ${r.from} ${r.cardinality} ${r.to}`);\n lines.push('');\n }\n lines.push(`CREATE OR ALTER TABLE DEMO_DB.${t.schema}.${t.name} (`);\n lines.push(colDdl.join(',\\n'));\n lines.push(')');\n if (t.note) lines.push(`COMMENT = '${t.note.replace(/'/g, \"''\")}'`);\n lines.push(';\\n');\n return lines.join('\\n');\n}\n\n/**\n * Translate DBML's database-agnostic type names into the closest\n * Snowflake equivalent. Naive — a real translation needs the DBML\n * file's `Project` directive's database setting. This default works\n * for the most common types.\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) {\n if (sourcePath.endsWith('.sdtpac')) {\n const c = await pac.readPac(sourcePath);\n return c.model;\n }\n const loaded = await project.loadProject(sourcePath);\n return await project.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 { pac, project, schema } from '@sdt-tools/core';\n\n/**\n * `sdt suggest` — propose foreign-key relationships, candidate\n * primary keys, unique-key candidates, and composite-PK candidates\n * for the tables in a project. Every suggestion ships with a\n * **reasoning sentence** so a reviewer understands *why* it was\n * proposed.\n *\n * **What this is**: a hint generator. We never mutate the model\n * behind the user's back.\n *\n * **What this is NOT**: erwin Data Modeler's \"Auto-FK\" or any\n * vendor's \"modeling wizard\". The heuristics are common-sense\n * conventions; the framing (reasoning + confidence tier) is ours.\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>', '.sdtproj or .sdtpac 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) {\n if (sourcePath.endsWith('.sdtpac')) {\n const c = await pac.readPac(sourcePath);\n return c.model;\n }\n const loaded = await project.loadProject(sourcePath);\n return await project.parseProjectModel(loaded);\n}\n","/**\n * `sdt safety` — inspect safety-finding codes.\n *\n * Subcommands:\n * sdt safety list — list every known finding code with a one-line summary\n * sdt 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 `sdt compare` / `sdt publish`. When the user\n * sees a finding they don't understand, they can copy the code and ask:\n *\n * sdt safety explain DROP_UNRECOVERABLE\n *\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 } from '@sdt-tools/core';\nimport type { FindingExplanation, SafetyFindingCode } from '@sdt-tools/core/safety';\nimport { logger } from '../util/logger.js';\n\nexport function safetyCommand(): Command {\n const cmd = new Command('safety');\n cmd.description(\n 'Inspect the safety-finding catalog. See `sdt safety list` and `sdt 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 logger.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 logger.dim('(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 logger.error(`Unknown safety finding code: \"${codeArg}\"`);\n logger.dim(' Try: sdt 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 `sdt 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\n/** Word-wrap a paragraph to fit `width` characters per line. */\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 * `sdt pii` — scan a project for PII columns and optionally generate\n * masking-policy DDL. Wraps `@sdt-tools/core/pii`.\n *\n * Subcommands:\n * sdt pii scan — list candidates (table | json | markdown)\n * sdt pii mask — render the anonymisation script\n *\n * The `--ai` flag on `scan` routes ambiguous candidates through the\n * configured AI provider for a second opinion (uses\n * `@sdt-tools/core/ai.complete()`).\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { ai, pac, pii, project } from '@sdt-tools/core';\nimport { logger } from '../util/logger.js';\n\nexport function piiCommand(): Command {\n const cmd = new Command('pii');\n cmd.description(\n 'Detect PII columns + render Snowflake MASKING POLICY DDL. See `sdt pii scan` and `sdt pii mask`.',\n );\n\n cmd\n .command('scan')\n .description('Scan the project for PII column candidates.')\n .requiredOption('--source <path>', '.sdtproj or .sdtpac 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 Snowflake MASKING POLICY DDL for detected PII columns.')\n .requiredOption('--source <path>', '.sdtproj or .sdtpac to scan.')\n .option(\n '--unmasked-role <name>',\n \"Role that sees the unmasked value. Default 'PROD_ETL'.\",\n 'PROD_ETL',\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(async (opts: { source: string; unmaskedRole?: string; ai?: boolean; out?: string }) => {\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 logger.warn('No PII columns detected.');\n return;\n }\n const sql = pii.renderAnonymizeScript(candidates, {\n unmaskedRole: String(opts.unmaskedRole ?? 'PROD_ETL'),\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 logger.success(`Wrote ${outPath} (${candidates.length} candidate(s), ${sql.length} bytes).`);\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) {\n if (sourcePath.endsWith('.sdtpac')) {\n const c = await pac.readPac(sourcePath);\n return c.model;\n }\n const loaded = await project.loadProject(sourcePath);\n return await project.parseProjectModel(loaded);\n}\n","/**\n * `sdt bisect <fqn>` — find the commit where a specific Snowflake object\n * first changed in a git-tracked `.sdtproj` project tree.\n *\n * Mirrors `Databricks/packages/cli/src/commands/bisect.ts` byte-for-byte\n * in flow; only the project loader + object-type defaults are Snowflake-\n * flavored.\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 '@sdt-tools/core/project';\nimport type { SnowflakeObjectType } from '@sdt-tools/core/model';\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 (database.schema.name).')\n .option('-p, --project <path>', 'Path to the .sdtproj 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 SnowflakeObjectType;\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 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 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 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 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 if (opts.format === 'json') {\n console.log(JSON.stringify({ fqn: fqnArg, objectType, path: relPath, entries }, null, 2));\n return;\n }\n if (entries.length === 0) {\n console.log(`No commits found for ${objectType} ${fqnArg} (path: ${relPath}).`);\n return;\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 * `sdt changelog --from <ref> --to <ref>` — auto-generate a\n * Markdown CHANGELOG section from git commits between two refs.\n *\n * Parses Conventional Commits (`feat:`, `fix:`, `chore:`, `docs:`,\n * `refactor:`, `perf:`, `test:`, `build:`, `style:`, `ci:`),\n * groups commits by category, and emits a release section.\n * Deterministic — no AI dependency. Mirrors `ddt changelog`.\n *\n * Use case: release prep. Cut a tag, run\n * `sdt changelog --from v0.4.0 --to v0.5.0 -o CHANGELOG.md`,\n * commit the updated CHANGELOG with the tag.\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. `Snowflake/packages/cli/**`). Default: all paths.',\n )\n .option('-o, --out <path>', 'Append/write to file. Default: stdout.')\n .option(\n '--append',\n 'When --out is set, prepend to existing file (typical changelog behavior).',\n false,\n )\n .option(\n '--manifest-dir <path>',\n 'Directory containing deploy manifests (default: .sdt/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\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 // --manifest-dir: read deploy manifests, build a per-deploy\n // addendum that surfaces step status + safety counts. Default\n // dir matches `<tool> publish --apply --manifest` convention.\n const manifestDir = opts.manifestDir\n ? path.resolve(String(opts.manifestDir))\n : path.join(repo, '.sdt', '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 // No previous tag — fall back to the repo's root commit.\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 // Conventional Commits: <type>(<scope>)?: <subject>\n // Breaking-change marker is a trailing `!` before the colon.\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 // Map both 'ci' and 'build' to the same bucket via heading lookup.\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; // Already listed under BREAKING.\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 /** Manifest filename (no path), useful as the link target in markdown. */\n filename: string;\n /** ISO timestamp the deploy finished, when present in the manifest. */\n deployedAt?: string;\n /** Snowflake account or Databricks workspace host. */\n account?: string;\n /** clean-success / clean-partial / dirty / clean-skipped. */\n finalState?: string;\n /** Step id of the first failure (when finalState === 'dirty'). */\n failedStepId?: string | null;\n /** Per-status counts across all steps. */\n stepCounts: Record<string, number>;\n /** Total step count. */\n totalSteps: number;\n}\n\n/** Read every `<dir>/*.json` deploy manifest into a summary row. Best-effort. */\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 account?: 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.account === 'string' ? { account: parsed.account } : {}),\n ...(typeof parsed.finalState === 'string' ? { finalState: parsed.finalState } : {}),\n failedStepId: parsed.failedStepId ?? null,\n stepCounts,\n totalSteps: steps.length,\n });\n } catch {\n // Corrupt or missing — skip. Deploy manifests are append-only;\n // a half-written file is the rare exception.\n }\n }\n return out;\n}\n\n/** Render one DeploySummary as a Markdown bullet. */\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.account) parts.push(d.account);\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 * `sdt replay --manifest <path>` — re-execute a previous deploy's\n * forwardSql against a fresh target.\n *\n * Use cases:\n * - Rebuild a dev/stage account from production's manifest history.\n * - Reproduce a customer's failure by replaying their support-bundle\n * manifest against an internal sandbox.\n *\n * Mirrors `Databricks/packages/cli/src/commands/replay.ts`. Symmetric to\n * `sdt revert` — same manifest format, same executor, forward instead\n * of reverse.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { getProfile, SnowflakeConnection } from '@sdt-tools/core/connection';\nimport {\n SnowflakeExecutor,\n type DeployManifest,\n type DeployManifestStep,\n} from '@sdt-tools/core/deploy';\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 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 Snowflake account.',\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.account}`,\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 = new SnowflakeConnection(profile);\n let succeeded = 0;\n let failed = 0;\n try {\n await conn.connect();\n const executor = new SnowflakeExecutor(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 * `sdt drift-gate` — multi-region/replica drift gate.\n *\n * Compares the live schema in N replica accounts against a primary\n * account's live schema. Useful for orgs that replicate Snowflake\n * databases across regions (Snowflake replication, secondary databases)\n * and want a CI gate that fires the moment any replica drifts from the\n * primary.\n *\n * Mirrors `Databricks/packages/cli/src/commands/drift-gate.ts`.\n */\nimport { Command } from 'commander';\nimport { CompareEngine, LiveSource } from '@sdt-tools/core/compare';\nimport { getProfile, SnowflakeConnection } from '@sdt-tools/core/connection';\n\ninterface RegionResult {\n profile: string;\n account: 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 Snowflake accounts. Compares replicas against a primary.',\n )\n .requiredOption('--primary <profile>', 'Primary account connection profile.')\n .requiredOption('--replicas <list>', 'Comma-separated replica connection profile names.')\n .option('--database <database>', 'Limit drift comparison to a single database.')\n .option('--schema <schema>', 'Limit drift comparison to a single schema (requires --database).')\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 primaryProfile = 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.database ? { database: String(opts.database) } : {}),\n ...(opts.schema ? { schema: String(opts.schema) } : {}),\n };\n\n const primaryConn = new SnowflakeConnection(primaryProfile);\n const primarySource = new LiveSource(primaryConn, scope, `primary:${primaryProfile.account}`);\n\n const results: RegionResult[] = [];\n const engine = new CompareEngine();\n\n try {\n // Pre-load primary once so the source's lazy load happens here.\n await primarySource.load();\n\n for (const replicaName of replicaNames) {\n const replicaProfile = await getProfile(replicaName);\n const replicaConn = new SnowflakeConnection(replicaProfile);\n const replicaSource = new LiveSource(\n replicaConn,\n scope,\n `replica:${replicaProfile.account}`,\n );\n try {\n const result = await engine.compare(primarySource, replicaSource);\n const { added, removed, modified } = result.summary;\n results.push({\n profile: replicaName,\n account: replicaProfile.account,\n added,\n removed,\n modified,\n total: added + removed + modified,\n });\n } finally {\n await replicaConn.disconnect();\n }\n }\n } finally {\n await primaryConn.disconnect();\n }\n\n if (opts.format === 'json') {\n console.log(\n JSON.stringify(\n { primary: primaryProfile.account, threshold, replicas: results },\n null,\n 2,\n ),\n );\n } else {\n console.log(`Drift gate — primary ${primaryProfile.account}`);\n console.log('');\n console.log(\n ' REPLICA-PROFILE ACCOUNT 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.account.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 * `sdt promote --from <profile> --to <profile>` — branch-per-env deploy\n * automation.\n *\n * Compares two live Snowflake accounts (dev→stage, stage→prod), generates\n * 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 * Mirrors `Databricks/packages/cli/src/commands/promote.ts`.\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 { CompareEngine, LiveSource } from '@sdt-tools/core/compare';\nimport {\n ScriptGenerator,\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 '@sdt-tools/core/deploy';\nimport {\n assess,\n groupByReversibility,\n formatReversibilityBuckets,\n type SafetyAssessment,\n} from '@sdt-tools/core/safety';\nimport { getProfile, SnowflakeConnection } from '@sdt-tools/core/connection';\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('--from <profile>', 'Source environment connection profile (e.g. dev).')\n .option('--to <profile>', 'Target environment connection profile (e.g. stage).')\n .option('--database <database>', 'Limit to a single database.')\n .option('--schema <schema>', 'Limit to a single schema (requires --database).')\n .option(\n '--from-profile <path>',\n 'Path to source promotion profile JSON (parsed via parsePromotionProfile). ' +\n 'Defaults to `.sdt/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 `.sdt/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: sdt-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.database ? { database: String(opts.database) } : {}),\n ...(opts.schema ? { schema: String(opts.schema) } : {}),\n };\n\n const fromConn = new SnowflakeConnection(fromProfile);\n const toConn = new SnowflakeConnection(toProfile);\n const fromSource = new LiveSource(fromConn, scope, `from:${fromProfile.account}`);\n const toSource = new LiveSource(toConn, scope, `to:${toProfile.account}`);\n\n const engine = new CompareEngine();\n let result;\n try {\n result = await engine.compare(fromSource, toSource);\n } finally {\n await fromConn.disconnect();\n await toConn.disconnect();\n }\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 const generator = new ScriptGenerator();\n const script = generator.generate(result, {});\n const safetyAssessment = assess(result);\n\n const fromPromotionProfile = await loadPromotionProfileForCli(\n opts.fromProfile ? String(opts.fromProfile) : undefined,\n String(opts.from),\n '.sdt',\n '--from-profile',\n );\n const toPromotionProfile = await loadPromotionProfileForCli(\n opts.toProfile ? String(opts.toProfile) : undefined,\n String(opts.to),\n '.sdt',\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 const lines: string[] = [];\n lines.push(`# Promote: ${String(opts.from)} → ${String(opts.to)}`);\n lines.push('');\n lines.push(`Generated by \\`sdt 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 = groupByReversibility(safetyAssessment);\n lines.push(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 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 ?? `sdt-promote/${String(opts.from)}-to-${String(opts.to)}-${Date.now()}`,\n );\n const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'sdt-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 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 .sdt/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 * `sdt data-fit --source <pac> --target <pac>` — generate pre-flight\n * data-fit probe queries for narrowing type changes.\n *\n * Walks the source-vs-target compare, finds every TABLE / ICEBERG_TABLE\n * / HYBRID_TABLE / EVENT_TABLE / DYNAMIC_TABLE whose column-level diff\n * includes a type change, classifies each change via\n * `@sdt-tools/core/types.classifyTypeChange`, and for every\n * `data-fit-required` verdict emits a `SELECT count_if(...)` probe via\n * `dataFitProbeSql`.\n *\n * The probe queries are deliberately **read-only** — they run against\n * the target without modifying state. The operator runs them before\n * `sdt publish --apply` to confirm zero rows would overflow the\n * narrower type.\n *\n * Each query is wrapped in a `-- PROBE: <fqn>.<column> (<from> → <to>)`\n * header so DBA review is easy.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { CompareEngine, PacSource } from '@sdt-tools/core/compare';\nimport { classifyTypeChange, dataFitProbeSql } from '@sdt-tools/core/types';\nimport type { AnySnowflakeObject } from '@sdt-tools/core/model';\n\ninterface ColumnWithType {\n name: string;\n /** Either a `SnowflakeDataType` struct or a raw string (best-effort). */\n dataType: unknown;\n}\n\nfunction getColumns(obj: AnySnowflakeObject): 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 return cols as ColumnWithType[];\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 quotedFqn(obj: AnySnowflakeObject): 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 quotedCol(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>', '.sdtpac with the desired state.')\n .requiredOption('--target <path>', '.sdtpac 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 = classifyTypeChange(fromStr, toStr);\n if (check.verdict !== 'data-fit-required') continue;\n const fqn = quotedFqn(obj.source);\n const colName = pair.source.name;\n const probeSql = dataFitProbeSql(check, fqn, quotedCol(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 \\`sdt 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}.${quotedCol(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 \\`sdt 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 * `sdt 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 `SnowflakeConnection.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 * sdt data-compare --table DB.S.T --key ID \\\n * --source rows-source.json --target rows-target.json\n *\n * Usage (live):\n * sdt data-compare --table DB.S.T --key ID \\\n * --source-live dev --target-live prod \\\n * [--columns ID,EMAIL,STATUS] [--row-limit 50000]\n *\n * Mirrors `ddt data-compare`.\n */\nimport { promises as fs } from 'fs';\nimport path from 'path';\nimport { Command } from 'commander';\nimport { dataCompare } from '@sdt-tools/core';\nimport { getProfile, SnowflakeConnection } from '@sdt-tools/core/connection';\nimport { logger } from '../util/logger.js';\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 (DATABASE.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 — Snowflake idiom).',\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, 'snowflake');\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 logger.info(\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 = new SnowflakeConnection(profile);\n logger.step(\n `data-compare (${side}): connecting to ${profile.account} as ${profile.auth.username}…`,\n );\n await conn.connect();\n try {\n const rows = await conn.executeRows(sql);\n logger.info(\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 * `sdt approval` — manage multi-approver gate tokens (Team-tier).\n *\n * sdt approval add <deploy-id> --as <approver> [--message <text>] [--digest <hex>]\n * sdt approval list <deploy-id>\n * sdt approval clear <deploy-id>\n * sdt approval check <deploy-id> --required N --allowed <ids>\n *\n * Tokens default to `.sdt/approvals/` under the current working\n * directory; override with `--root <path>` on every subcommand.\n *\n * Mirrors `ddt approval`.\n */\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { approval } from '@sdt-tools/core';\n\nconst DEFAULT_ROOT = path.join('.sdt', '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 * `sdt 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 * `@sdt-tools/core/features.SDT_FEATURE_CATALOG`, and asks the configured AI\n * provider to recommend a minimal regression-test set.\n *\n * Mirrors `ddt advise-tests`.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { ai, regressionAdvisor } from '@sdt-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 SDT 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, 'sdt');\n });\n return cmd;\n}\n\nexport async function runAdviseTests(\n opts: Record<string, unknown>,\n toolName: 'sdt' | '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 * `sdt safer-alternative` — call the AI provider to suggest a safer DDL\n * alternative for a flagged-as-dangerous migration step.\n *\n * Composes `@sdt-tools/core/saferAlternative.suggestSaferAlternative` with the\n * configured AI provider (`@sdt-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. TABLE, STREAM)\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 '@sdt-tools/core';\nimport { logger } from '../util/logger.js';\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 (sdt 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. TABLE, VIEW, STREAM).')\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 // Strip rawModelText from JSON output by default — it bloats the\n // payload for downstream tooling. Keep it accessible via --format text.\n const { rawModelText: _omit, ...keep } = result;\n console.log(JSON.stringify(keep, null, 2));\n return;\n }\n\n logger.success(\n `Confidence: ${result.confidence}${result.parseFailed ? ' (parse failed)' : ''}`,\n );\n logger.dim(`Reasoning: ${result.reasoning}`);\n if (result.alternativeSql) {\n console.log('');\n console.log('--- Proposed safer DDL ---');\n console.log(result.alternativeSql);\n } else {\n logger.warn('No safer alternative SQL was returned.');\n }\n if (result.requiredGates.length > 0) {\n logger.dim(`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 * `sdt sketch <kind>` — generate idiomatic Snowflake DDL from a free-form\n * prose description via the configured AI provider.\n *\n * Composes `@sdt-tools/core/objectSketch.sketchToDdl` with `@sdt-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> table | view | materialized-view | stream | task\n * | dynamic-table | procedure | function | sequence\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 '@sdt-tools/core';\nimport { logger } from '../util/logger.js';\n\nconst KINDS = [\n 'table',\n 'view',\n 'materialized-view',\n 'stream',\n 'task',\n 'dynamic-table',\n 'procedure',\n 'function',\n 'sequence',\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 Snowflake 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 role MERGE_OPS\").')\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 } /* strip raw for JSON */, null, 2)\n : result.generatedSql;\n\n if (opts.out) {\n await fs.writeFile(String(opts.out), output, 'utf8');\n logger.success(`Wrote ${String(opts.out)} (${output.length} bytes)`);\n } else {\n console.log(output);\n }\n\n // Surface assumptions on stderr so they're visible even when stdout\n // is redirected into a project file.\n if (result.assumptions.length > 0) {\n logger.dim('');\n logger.dim('Model assumptions:');\n for (const a of result.assumptions) logger.dim(` - ${a}`);\n }\n if (result.parseFailed) {\n logger.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): { 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 if (parts.length === 3) return { database: 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 * `sdt 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 `@sdt-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 `ddt design`.\n */\nimport { Command } from 'commander';\nimport { ai, designSnowflakeSchema, designStar } from '@sdt-tools/core';\nimport { logger } from '../util/logger.js';\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 `sdt 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. ANALYTICS.PUBLIC).')\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 `sdt 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. ANALYTICS.CORE).')\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 'sdt',\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 logger.dim('');\n logger.dim('Model assumptions:');\n for (const a of result.assumptions) logger.dim(` - ${a}`);\n }\n if (result.parseFailed) {\n logger.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 'sdt',\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 logger.dim('');\n logger.dim('Model assumptions:');\n for (const a of result.assumptions) logger.dim(` - ${a}`);\n }\n if (result.parseFailed) {\n logger.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 (database[.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 * `sdt optimize` — heuristic optimizer. Walks the model and surfaces\n * ranked recommendations (clustering, narrowing, missing PKs, dynamic-\n * table target-lag). Composes with `--explain` so the configured AI\n * provider can re-rank and contextualise.\n *\n * Mirrors `ddt optimize`.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { optimize, pac, project } from '@sdt-tools/core';\nimport type { SnowflakeObject } from '@sdt-tools/core/model';\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 (clustering, narrowing, missing PKs, dynamic-table lag).',\n )\n .requiredOption('--source <path>', '.sdtproj or .sdtpac 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 Snowflake performance engineer. Walk the team through these optimization recommendations: which would have the biggest 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 SnowflakeObject[]> {\n if (sourcePath.endsWith('.sdtpac')) {\n const c = await pac.readPac(sourcePath);\n return c.model as unknown as readonly SnowflakeObject[];\n }\n const loaded = await project.loadProject(sourcePath);\n return (await project.parseProjectModel(loaded)) as readonly SnowflakeObject[];\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 * `sdt 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 `sdt 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 `ddt rollback-suggest`.\n */\nimport { promises as fs } from 'node:fs';\nimport { Command } from 'commander';\nimport { ai, aiRollback } from '@sdt-tools/core';\nimport { logger } from '../util/logger.js';\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('--object-type <type>', 'Optional object type for context (e.g. TABLE, STREAM).')\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 logger.success(\n `Confidence: ${result.confidence}${result.unrecoverable ? ' (UNRECOVERABLE)' : ''}${result.parseFailed ? ' — parse failed' : ''}`,\n );\n logger.dim(`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 * `sdt 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>/.sdt/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>/.sdt/cache/<reference>/catalog.msgpack` (legacy\n * `catalog.json` also accepted). Run\n * `sdt catalog refresh --connection <reference>` first.\n * - kind=pac — reads the `.sdtpac` archive at `reference`.\n * - kind=project — reads the `.sdtproj` at `reference`.\n */\nimport { promises as fs } from 'node:fs';\nimport { Command } from 'commander';\nimport { catalog, compareProfiles, pac, project } from '@sdt-tools/core';\nimport type { FullyQualifiedName, SnowflakeObject } from '@sdt-tools/core/model';\nimport { logger } from '../util/logger.js';\n\nexport function compareProfilesCommand(): Command {\n const cmd = new Command('compare-profiles');\n cmd.description('Manage saved compare profiles (.sdt/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 logger.dim('(no compare profiles saved yet)');\n logger.dim(` store: ${store.path}`);\n return;\n }\n logger.success(`${all.length} compare profile(s):`);\n for (const p of all) {\n console.log(` ${p.id.padEnd(24)} ${p.name}`);\n logger.dim(` source: ${p.source.kind}=${p.source.reference}`);\n logger.dim(` target: ${p.target.kind}=${p.target.reference}`);\n logger.dim(` 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 logger.error(`No profile with id \"${id}\". Run \\`sdt compare-profiles list\\` to enumerate.`);\n process.exitCode = 1;\n return;\n }\n if (opts.json) {\n console.log(JSON.stringify(p, null, 2));\n return;\n }\n logger.success(`Profile: ${p.name} (${p.id})`);\n if (p.description) logger.dim(` ${p.description}`);\n logger.dim(\n ` source: ${p.source.kind}=${p.source.reference}${p.source.database ? ` db=${p.source.database}` : ''}${p.source.schema ? ` schema=${p.source.schema}` : ''}`,\n );\n logger.dim(\n ` target: ${p.target.kind}=${p.target.reference}${p.target.database ? ` db=${p.target.database}` : ''}${p.target.schema ? ` schema=${p.target.schema}` : ''}`,\n );\n logger.dim(` case-sensitive: ${p.caseSensitive ? 'yes' : 'no'}`);\n logger.dim(` rewrite-inside-strings: ${p.rewriteInsideStrings ? 'yes' : 'no'}`);\n logger.dim(` updatedAt: ${p.updatedAt}`);\n if (p.mappings.length === 0) {\n logger.dim(' mappings: (none — identity)');\n } else {\n logger.dim(` mappings (${p.mappings.length}):`);\n for (const m of p.mappings) logger.dim(` ${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 logger.success(`Saved profile \"${stamped.name}\" (${stamped.id})`);\n logger.dim(` 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 logger.success(`Removed profile \"${id}\".`);\n } else {\n logger.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 warehouse 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 logger.error(`No profile with id \"${id}\". Run \\`sdt compare-profiles list\\` to enumerate.`);\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 logger.success(`Preview: ${profile.name} (${profile.id})`);\n logger.dim(\n ` source (${profile.source.kind}=${profile.source.reference}): ${source.fqns.length} object(s)${source.note ? ` — ${source.note}` : ''}`,\n );\n logger.dim(\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 logger.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.databases.length === 0) {\n return {\n fqns: [],\n note: `empty catalog cache at ${cache.path} — run \\`sdt catalog refresh --connection ${endpoint.reference}\\` first`,\n };\n }\n return { fqns: fqnsFromSnapshot(snapshot, endpoint.database, endpoint.schema) };\n }\n if (endpoint.kind === 'pac') {\n const contents = await pac.readPac(endpoint.reference);\n return { fqns: fqnsFromObjects(contents.model, endpoint.database, endpoint.schema) };\n }\n // kind === 'project'\n const loaded = await project.loadProject(endpoint.reference);\n const model = await project.parseProjectModel(loaded);\n return { fqns: fqnsFromObjects(model, endpoint.database, endpoint.schema) };\n}\n\nfunction fqnsFromSnapshot(\n snapshot: catalog.CatalogSnapshot,\n databaseScope: 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 db of snapshot.databases) {\n if (databaseScope && !sameId(db.database, databaseScope)) continue;\n for (const sc of db.schemas) {\n if (schemaScope && !sameId(sc.schema, schemaScope)) continue;\n for (const obj of sc.objects) {\n out.push({ database: obj.database, schema: obj.schema, name: obj.name });\n }\n }\n }\n return out;\n}\n\nfunction fqnsFromObjects(\n model: readonly SnowflakeObject[],\n databaseScope: 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 if (databaseScope && !sameId(obj.fqn.database, databaseScope)) 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 * `sdt explorer` — ASCII tree dump of the live db/schema/object hierarchy\n * 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 `sdt 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 .sdt/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 '@sdt-tools/core';\nimport { logger } from '../util/logger.js';\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 `sdt 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 = +databases, 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.databases.length === 0) {\n logger.warn(`Catalog cache is empty for connection \"${opts.connection}\".`);\n logger.dim(` Cache file: ${cache.path}`);\n logger.dim(` Run \\`sdt 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 * `sdt catalog` — manage the per-connection catalog cache (EE1 substrate).\n *\n * sdt catalog refresh --connection <name> [--databases <csv>] [--concurrency <n>]\n * sdt catalog show --connection <name> [--json]\n * sdt catalog clear --connection <name>\n *\n * `refresh` opens a live Snowflake connection, discovers databases via\n * `SHOW DATABASES`, runs the bulk-scan SQL per database via the bounded\n * promise pool, and writes the assembled snapshot to\n * `<root>/.sdt/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; databases 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 (`sdt explorer`) and the eventual EE2 intellisense\n * provider both consume this cache.\n */\nimport { Command } from 'commander';\nimport { catalog } from '@sdt-tools/core';\nimport { getProfile, SnowflakeConnection } from '@sdt-tools/core/connection';\nimport { logger } from '../util/logger.js';\n\n/**\n * Built-in databases that almost no one wants in their cache. Pass\n * `--include-builtins` to keep them.\n */\nconst BUILTIN_DATABASES = new Set(['SNOWFLAKE', 'SNOWFLAKE_SAMPLE_DATA', 'UTIL_DB']);\n\ninterface ShowDatabasesRow {\n name?: string;\n 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) database, write the catalog cache.')\n .requiredOption('-c, --connection <name>', 'Connection profile name.')\n .option('--root <path>', 'Project root. Default cwd.', process.cwd())\n .option('--databases <csv>', 'Comma-separated list. Default: every non-builtin database.')\n .option('--include-builtins', 'Include SNOWFLAKE / SNOWFLAKE_SAMPLE_DATA / UTIL_DB.', 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 = new SnowflakeConnection(profile);\n const cache = new catalog.CatalogCache({\n root: String(opts.root),\n connection: profile.name,\n });\n\n logger.step(`Connecting to ${profile.account} as ${profile.auth.username}…`);\n await conn.connect();\n try {\n const dbs = await resolveDatabases(conn, opts);\n if (dbs.length === 0) {\n logger.warn('No databases to scan. Pass --databases or --include-builtins.');\n return;\n }\n logger.dim(\n `Scanning ${dbs.length} database(s) with concurrency ${Number(opts.concurrency)}.`,\n );\n\n const cached = await cache.get();\n const cachedByDb = new Map(cached.databases.map((d) => [d.database, d] 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 dbs,\n async (db) => {\n // Cheap fingerprint probe first.\n let freshFingerprint: number | null = null;\n try {\n const fpRes = await conn.query<{ MAX_LAST_ALTERED: unknown }>(\n catalog.fingerprintSqlForDatabase(db),\n );\n freshFingerprint = catalog.parseFingerprintRow(fpRes.rows);\n } catch (err) {\n logger.warn(\n `fingerprint(${db}) failed; falling through to full scan: ${(err as Error).message}`,\n );\n }\n\n const cachedDb = cachedByDb.get(db);\n if (\n fingerprintSkip &&\n cachedDb &&\n cachedDb.fingerprint != null &&\n freshFingerprint != null &&\n catalog.isFresh(cachedDb.fingerprint, freshFingerprint)\n ) {\n logger.dim(` ${db}: fresh; reusing cache`);\n return { database: db, fingerprint: cachedDb.fingerprint, schemas: cachedDb.schemas };\n }\n\n const scanRes = await conn.query(catalog.bulkScanSqlForDatabase(db));\n const schemas = catalog.parseBulkScanRows(db, scanRes.rows);\n const fingerprint = freshFingerprint ?? null;\n logger.dim(\n ` ${db}: ${schemas.length} schemas / ${schemas.reduce((sum, s) => sum + s.objects.length, 0)} objects`,\n );\n return { database: db, fingerprint, schemas };\n },\n { concurrency },\n );\n\n for (const e of errors) {\n logger.warn(`scan failed for \"${dbs[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 databases: results.filter((r): r is NonNullable<typeof r> => !!r),\n });\n await cache.set(snapshot);\n\n logger.success(`Wrote ${snapshot.databases.length} databases 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.databases.length === 0) {\n logger.warn(`Catalog cache is empty for \"${opts.connection}\".`);\n logger.dim(` Cache file: ${cache.path}`);\n logger.dim(` Run \\`sdt catalog refresh --connection ${opts.connection}\\` to populate.`);\n return;\n }\n logger.success(`Snapshot for \"${snapshot.connection}\" — ${snapshot.snapshotAt}`);\n logger.dim(\n ` Top-level fingerprint: ${snapshot.fingerprint != null ? new Date(snapshot.fingerprint).toISOString() : '(none)'}`,\n );\n for (const db of snapshot.databases) {\n const objCount = db.schemas.reduce((sum, s) => sum + s.objects.length, 0);\n console.log(\n ` ${db.database.padEnd(32)} ${db.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 logger.success(`Cleared cache for \"${opts.connection}\".`);\n logger.dim(` was: ${cache.path}`);\n });\n\n return cmd;\n}\n\nasync function resolveDatabases(\n conn: SnowflakeConnection,\n opts: { databases?: unknown; includeBuiltins?: unknown },\n): Promise<string[]> {\n if (opts.databases) {\n return String(opts.databases)\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean);\n }\n const res = await conn.query<ShowDatabasesRow>('SHOW DATABASES');\n const names = res.rows.map((r) => String(r.name ?? r.NAME ?? '')).filter(Boolean);\n if (opts.includeBuiltins) return names;\n return names.filter((n) => !BUILTIN_DATABASES.has(n.toUpperCase()));\n}\n","/**\n * `sdt xcompare-ir` — Cross-platform IR compare (XPM.31b).\n *\n * Reads a JSON file of source-platform canonical IRs (typically the\n * Snowflake 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 `<ddt-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 * sdt xcompare-ir --source schema.json \\\n * --tier pro \\\n * --format markdown\n *\n * sdt 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 '@sdt-tools/core/migrate';\nimport type { XpmObjectIr } from '@sdt-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 (Snowflake ↔ Databricks). 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 * `sdt 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 `SnowflakeConnection.executeRows`.\n *\n * Live mode runs `SELECT * FROM <fqn>` (LIMIT --row-limit) against the\n * configured profile. Composes with `sdt suggest-constraints` (item 5).\n *\n * Mirrors `ddt profile`.\n */\nimport { promises as fs } from 'fs';\nimport path from 'path';\nimport { Command } from 'commander';\nimport { profile } from '@sdt-tools/core';\nimport { getProfile, SnowflakeConnection } from '@sdt-tools/core/connection';\nimport { logger } from '../util/logger.js';\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 (DATABASE.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 Snowflake 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 await fs.writeFile(path.resolve(String(opts.output)), output, 'utf8');\n logger.info(`Wrote profile to ${opts.output}`);\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 = new SnowflakeConnection(cp);\n logger.step(`profile: connecting to ${cp.account} as ${cp.auth.username}…`);\n await conn.connect();\n try {\n const rows = await conn.executeRows(sql);\n logger.info(\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 * `sdt suggest-constraints <fqn>` — item 5 of the constraint-enforcement\n * initiative. Reads a TableProfile JSON file (from `sdt profile`) plus\n * an optional parent-PKs JSON file, and emits heuristic PK/UK/FK/CHECK\n * candidates.\n *\n * v1 ships the heuristic path; `--ai` re-rank by business plausibility\n * and `--apply` (writes to refactor.json via applyChatOps) land in\n * follow-ups so this commit stays scope-bounded.\n *\n * Mirrors `ddt suggest-constraints`.\n */\nimport { promises as fs } from 'fs';\nimport path from 'path';\nimport { Command } from 'commander';\nimport type { profile as profileNs } from '@sdt-tools/core';\nimport { ai, suggestConstraints as core, refactoring } from '@sdt-tools/core';\nimport { logger } from '../util/logger.js';\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 `sdt 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 (Hybrid Table semantics).',\n false,\n )\n .option(\n '--ai',\n 'After heuristic scoring, re-rank by business plausibility via the configured AI provider. Requires `sdt 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 logger.warn(\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 logger.warn(\n `--ai re-rank failed; keeping heuristic ordering: ${err instanceof Error ? err.message : String(err)}`,\n );\n logger.warn('Run `sdt 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 logger.info(\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 await fs.writeFile(path.resolve(String(opts.output)), output, 'utf8');\n logger.info(`Wrote ${suggestions.length} suggestion(s) to ${opts.output}`);\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: '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 kind = mapKind(s.kind);\n const details: refactoring.AddConstraintOp['details'] = {\n constraintKind: 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 mapKind(k: core.ConstraintKind): 'PRIMARY_KEY' | 'UNIQUE' | 'FOREIGN_KEY' | 'CHECK' {\n return k;\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 * `sdt export` — emit an SDT project in another format.\n *\n * v1 supports:\n * - `dcm` — Snowflake DCM Projects (manifest.yml + DEFINE files). The\n * best-of-both-worlds bridge: author + AI-review + lint in SDT,\n * deploy via DCM. See docs/CONSTRAINT_ENFORCEMENT.md and the DCM\n * parity initiative entries in docs/BACKLOG.md.\n *\n * Snowflake-only. DDT side does not ship `ddt export dcm` because DCM\n * Projects is a Snowflake-native feature.\n */\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { exporters, compare } from '@sdt-tools/core';\nimport type { project } from '@sdt-tools/core';\nimport { logger } from '../util/logger.js';\n\nexport function exportCommand(): Command {\n const cmd = new Command('export');\n cmd.description('Export an SDT project to another format (DCM, etc.). v1 supports `dcm` only.');\n\n cmd\n .command('dcm')\n .description(\n 'Emit a Snowflake DCM Projects directory (manifest.yml + DEFINE files) from an .sdtproj. ' +\n 'Best-of-both-worlds bridge — author + AI-review + lint in SDT, deploy via EXECUTE DCM PROJECT.',\n )\n .requiredOption('--source <path>', 'Path to the .sdtproj to export.')\n .requiredOption('--output <dir>', 'Output directory for the DCM project.')\n .option(\n '--dcm-project <fqn>',\n 'Override the DCM project FQN for every configuration (e.g. PROD_DB.PUBLIC.MY_PROJECT).',\n )\n .action(async (opts: { source: string; output: string; dcmProject?: string }) => {\n const sourcePath = path.resolve(opts.source);\n const outputDir = path.resolve(opts.output);\n const source = new compare.ProjectSource(sourcePath);\n const model = await source.load();\n // ProjectSource doesn't expose the raw SdtProject — read it\n // directly via fs for the manifest mapping.\n const fs = await import('node:fs/promises');\n const projectRaw = JSON.parse(await fs.readFile(sourcePath, 'utf8')) as project.SdtProject;\n const profiles = projectRaw.deploymentProfiles ?? { default: undefined };\n const dcmProjectFqnByConfig = opts.dcmProject\n ? Object.fromEntries(Object.keys(profiles).map((name) => [name, opts.dcmProject!]))\n : undefined;\n const result = await exporters.exportToDcm({\n projectPath: sourcePath,\n project: projectRaw,\n model: model as Parameters<typeof exporters.exportToDcm>[0]['model'],\n outputDir,\n ...(dcmProjectFqnByConfig ? { dcmProjectFqnByConfig } : {}),\n });\n logger.info(`Wrote ${result.filesWritten} DEFINE file(s) + manifest.yml to ${outputDir}`);\n for (const w of result.warnings) logger.warn(w);\n });\n\n return cmd;\n}\n","/**\n * `sdt purge` — DCM compatibility item 2.\n *\n * Generates a DROP script for every object in the project. The operator\n * runs the script explicitly — purge is destructive enough that v1\n * does not auto-execute.\n *\n * Mirrors DCM's `EXECUTE DCM PROJECT <n> PURGE` semantic. Honours every\n * per-type drop gate already in the safety classifier — set them via\n * --allow-* flags to relax. Default: refuses everything until each\n * relevant gate is flipped.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { compare, purge } from '@sdt-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 — relax with --allow-* flags.',\n )\n .requiredOption('--source <path>', '.sdtproj or .sdtpac 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 (STREAM/PIPE/TASK).',\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 compare.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 // Purge means we WANT drops — clear the default skip-list.\n doNotDropObjectTypes: [],\n preserveTargetOnlyObjects: false,\n blockOnPossibleDataLoss: false,\n },\n },\n targetLabel: 'target (purge)',\n });\n const header =\n `-- PURGE script generated by sdt — 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 * `sdt preview <fqn>` — DCM compatibility item 3.\n *\n * Sample-data inspector. SELECT * FROM <fqn> LIMIT <n> against a\n * connection profile, rendered as table or JSON.\n *\n * Mirrors DCM's `EXECUTE DCM PROJECT <n> PREVIEW`.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { preview } from '@sdt-tools/core';\nimport { getProfile, SnowflakeConnection } from '@sdt-tools/core/connection';\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 (DB.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 = new SnowflakeConnection(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 * `sdt refresh` — DCM compatibility item 4.\n *\n * Standalone refresh — emits ALTER DYNAMIC TABLE ... REFRESH + ALTER\n * TASK ... RESUME for every dynamic table / task in the project.\n *\n * Mirrors DCM's `EXECUTE DCM PROJECT <n> REFRESH ALL`.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { compare, refresh } from '@sdt-tools/core';\n\nexport function refreshCommand(): Command {\n return new Command('refresh')\n .description(\n 'Generate a REFRESH script for the dynamic tables + tasks in the project. ' +\n 'Operator runs the output script explicitly.',\n )\n .requiredOption('--source <path>', '.sdtproj or .sdtpac defining the objects.')\n .option('--no-dynamic-tables', 'Skip ALTER DYNAMIC TABLE ... REFRESH entries.', false)\n .option('--no-tasks', 'Skip ALTER TASK ... RESUME entries.', 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 compare.ProjectSource(sourcePath);\n const model = await source.load();\n const result = refresh.generateRefreshScript(\n model as Parameters<typeof refresh.generateRefreshScript>[0],\n {\n dynamicTables: opts.dynamicTables !== false,\n tasks: opts.tasks !== false,\n },\n );\n const header = `-- ${result.summary.dynamicTablesRefreshed} dynamic table(s) · ${result.summary.tasksResumed} task(s) resumed\\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, SDT_HINT_RULES } from '@sdt-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(), '.sdt', '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('sdt', SDT_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 sdt commands to get personalized suggestions.\\n',\n ),\n );\n console.log(chalk.dim(' Quick start:'));\n console.log(` ${chalk.cyan('sdt init')} initialize a new project`);\n console.log(` ${chalk.cyan('sdt build')} build a .sdtpac artifact`);\n console.log(` ${chalk.cyan('sdt compare')} compare project vs. live account`);\n console.log('');\n console.log(chalk.dim(' sdt features list · sdt 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('✔')} sdt ${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(`sdt ${c}`)}`);\n }\n console.log('');\n }\n\n console.log(chalk.dim(' sdt features list · sdt explain <topic>\\n'));\n });\n return cmd;\n}\n","/**\n * `sdt find <query>` — search the SDT feature catalog by keyword.\n *\n * DSC.1: surface any SDT capability by describing what you want to do.\n *\n * $ sdt find drift\n * $ sdt find \"multi-team database\"\n * $ sdt find compare --limit 3 --format json\n *\n * Reads the same catalog as `sdt 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 '@sdt-tools/core';\nimport { complete } from '@sdt-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 SDT 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 // DSC.4-followup — 24h-TTL disk cache at ~/.sdt/intent-cache.json.\n // Skipped entirely when --no-ai-cache is passed; otherwise:\n // load → check → maybe call → evict stale → save.\n const cachePath = path.join(homedir(), '.sdt', '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 — start fresh.\n }\n const cached = featuresApi.lookupIntent(cache, query);\n if (cached) {\n const idSet = new Set(cached.featureIds);\n const matchedFeatures = featuresApi.SDT_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.SDT_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 // Cache only AI-escalated results — Stage 1 deterministic hits\n // are already fast and don't need a cache round-trip.\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 — don't fail the command if disk is full.\n }\n }\n }\n } else {\n hits = featuresApi.searchFeatures(query, featuresApi.SDT_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: sdt features list · sdt 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(` sdt 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('sdt features list · sdt features show <id>\\n'),\n );\n });\n return cmd;\n}\n","/**\n * `sdt scan-secrets` — scan a project's DDL bodies for hardcoded credentials.\n *\n * Covers: passwords (IDENTIFIED BY), OAuth client_secret literals, AWS keys,\n * OpenAI keys, GitHub tokens, Slack tokens, JWTs, PEM private-key blocks,\n * Snowflake account-locator URLs, and generic high-entropy 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 `ddt scan-secrets`.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { pac, project, secretScanner } from '@sdt-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>', '.sdtproj or .sdtpac 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('.sdtpac')) {\n const c = await pac.readPac(sourcePath);\n return c.model;\n }\n const loaded = await project.loadProject(sourcePath);\n return await project.parseProjectModel(loaded);\n}\n","/**\n * `sdt error-lookup` — look up a failure in the known-error catalog (DSR.2).\n *\n * Usage:\n * sdt error-lookup --code OLS_LICENSE_EXPIRED\n * sdt error-lookup --fingerprint abcd1234deadbeef\n * sdt error-lookup --message \"License has expired\"\n * sdt 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 `ddt error-lookup`.\n */\nimport { Command } from 'commander';\nimport { errorCatalog } from '@sdt-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. OLS_LICENSE_EXPIRED).')\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 * `sdt deploy-status` — inspect resumable deploy checkpoints (DSR.3).\n *\n * Usage:\n * sdt deploy-status # list every resumable deploy\n * sdt deploy-status <deployId> # show one checkpoint\n * sdt deploy-status <deployId> --remove # delete a checkpoint\n * sdt deploy-status --format json # machine-readable list\n *\n * Mirrors `ddt deploy-status`.\n */\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { deployCheckpoint } from '@sdt-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 `sdt 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 * `sdt approval-chain` — M-of-N signed approval workflow (DSR.8).\n *\n * Subcommands:\n * sdt approval-chain keygen --out <dir> --id <approver>\n * Generate an Ed25519 keypair for an approver.\n * Writes <dir>/<approver>.pem and <dir>/<approver>.pub.pem.\n *\n * sdt approval-chain sign --deploy-id <id> --env <env>\n * --approver <id> --decision approve|reject\n * --key <private.pem> [--digest <hex>]\n * [--out <signed.json>]\n * Produce a signed approval record.\n *\n * sdt approval-chain verify --deploy-id <id> --env <env>\n * --config <approval.json>\n * --records <signed-records.json>\n * [--digest <hex>]\n * Evaluate the chain against the env policy.\n *\n * Mirrors `ddt 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 '@sdt-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 // derive kid from the public counterpart (Node lets us re-export from private)\n // Use the standard re-export path by importing crypto here.\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 * `sdt standards` — team SQL standards commands.\n *\n * Subcommands:\n * init — scaffold a starter `.sdt/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 '@sdt-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// `sdt standards init`\n// ─────────────────────────────────────────────────────────────────────\n\nfunction initSubcommand(): Command {\n const init = new Command('init');\n init\n .description(\n 'Scaffold a starter .sdt/standards.json config with sensible defaults. ' +\n 'Edit the file to match your team conventions, then run `sdt standards check`.',\n )\n .option(\n '--dir <path>',\n 'Project root directory containing or to receive .sdt/. Defaults to current directory.',\n )\n .option('--force', 'Overwrite an existing standards.json without prompting.')\n .option(\n '--preset <name>',\n 'Starter preset: \"default\" (Snowflake-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 sdtDir = path.join(projectRoot, '.sdt');\n const configPath = path.join(sdtDir, '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(sdtDir, { 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 `sdt standards check` to lint your SQL surface.');\n });\n return init;\n}\n\n// ─────────────────────────────────────────────────────────────────────\n// `sdt 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 .sdt/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 \\`sdt 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 \\`sdt 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 // Narrow the finding shape back to the runner's StandardsFinding.\n // The CLI input is a JSON-friendly subset; cast through `unknown` so\n // TypeScript doesn't complain about the family widening.\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// `sdt 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\n/**\n * Walk every `paths` entry and collect the absolute path of every `.sql`\n * file. Directories are walked recursively; explicit file paths are\n * included only when they have a `.sql` extension.\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 * `sdt 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 `Databricks/packages/cli/src/commands/perf.ts`.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { Command } from 'commander';\nimport { loadProject, parseProjectModel } from '@sdt-tools/core/project';\nimport {\n findMaterializedViewCandidates,\n findUnusedObjects,\n recommendWarehouseSize,\n renderMvCandidatesMarkdown,\n renderUnusedObjectsMarkdown,\n renderWarehouseSizingMarkdown,\n} from '@sdt-tools/core/perf';\nimport type { QueryHistoryEntry } from '@sdt-tools/core/queryHistory';\nimport { logger } from '../util/logger.js';\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 { __SDT_START_NS__?: bigint })\n .__SDT_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.__SDT_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(`sdt 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 .sdtproj file.')\n .requiredOption(\n '--history-file <path>',\n 'Path to a JSON file containing a QueryHistoryEntry[] (e.g. saved from `sdt 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 'EXTERNAL_TABLE',\n 'ICEBERG_TABLE',\n 'HYBRID_TABLE',\n 'DYNAMIC_TABLE',\n 'EVENT_TABLE',\n 'VIEW',\n 'MATERIALIZED_VIEW',\n ]);\n const fqns: string[] = [];\n for (const obj of model) {\n if (!testable.has(obj.objectType)) continue;\n const db = obj.fqn.database;\n const sc = obj.fqn.schema;\n if (!db || !sc) continue;\n fqns.push(`${db}.${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 logger.info(\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 `sdt 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 logger.info(\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-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 logger.info(\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 — `sdt migrate-platform --to databricks <path>`\n *\n * Translates Snowflake SQL files to Databricks equivalents using the XPM.3\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 `Databricks/packages/cli/src/commands/migrate-platform.ts`.\n */\nimport path from 'node:path';\nimport fs from 'node:fs/promises';\nimport { Command } from 'commander';\nimport { translateTableSnowflakeToDatabricks } from '@sdt-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 Snowflake SQL files to another platform dialect. ' +\n 'v1: --to databricks. 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 \"databricks\".')\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 !== 'databricks') {\n logger.error(\n `sdt migrate-platform --to ${opts.to}: unknown target. Only \"databricks\" is supported.`,\n );\n process.exitCode = 1;\n return;\n }\n\n const resolved = path.resolve(inputPath);\n // If the path is an .sdtproj file, translate its containing directory.\n const root = resolved.endsWith('.sdtproj') ? 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) → Databricks…`);\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 = translateTableSnowflakeToDatabricks(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 — `sdt 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:\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 `.sdtproj` + 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 `.sdtproj` + `.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 * SDT-only initially — Databricks mirror can land alongside DDT's own\n * CLI structure (Sonnet-scope sub-followup).\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 '@sdt-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 * `sdt 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 `Databricks/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 '@sdt-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 * `sdt watch` — platform-feature drift bulletin (WATCH.2-paired).\n *\n * Wires the shipped `@sdt-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 `Databricks/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 '@sdt-tools/core';\n\nconst DEFAULT_SOURCE = 'snowflake';\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 * `sdt bookmarks` — operator-facing CRUD over saved bookmarks (AUTH.6).\n *\n * Persists to `~/.sdt/bookmarks.json` (override with `--store <path>`).\n * Composes with the pure `@sdt-tools/core/bookmarks` substrate — this file\n * is the disk-I/O boundary; the substrate stays pure.\n *\n * Subcommands:\n * sdt bookmarks add <name> --type query|file|section --target <s> [--label <s>]\n * sdt bookmarks remove <name>\n * sdt bookmarks list [--format text|json]\n * sdt bookmarks get <name> [--format text|json]\n *\n * Mirrors `Databricks/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 '@sdt-tools/core';\n\nconst DEFAULT_STORE = path.join(os.homedir(), '.sdt', '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 `sdt 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 * `sdt snippets` — list + show the shipped snippets catalog (AUTH.2).\n *\n * Composes the pure `@sdt-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 * sdt snippets list [--category <c>] [--format text|json]\n * sdt snippets show <id> [--format text|json|raw]\n *\n * Mirrors `Databricks/packages/cli/src/commands/snippets.ts`.\n */\nimport { Command } from 'commander';\nimport { snippets } from '@sdt-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 `sdt 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 \\`sdt 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 * `sdt generate` — code generation CLI (GENPY.5).\n *\n * Three subcommands wiring GENPY.1/3/4 substrates onto the operator surface:\n *\n * sdt generate notebook --from-json <path> --target <fqn> --source <path>\n * [--runtime <ver>] [--merge-schema] [--write-mode append|overwrite]\n * [--out <dir>]\n *\n * sdt 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 * sdt generate star-pipeline --from-design <path>\n * [--format pyspark|sparksql|snowpark]\n * [--schema <catalog.schema>] [--out <dir>]\n *\n * Mirrors `Databricks/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, deploy } from '@sdt-tools/core';\n\n// ── notebook ──────────────────────────────────────────────────────────────────\n\nfunction notebookSubcommand(): Command {\n return new Command('notebook')\n .description('Emit a Snowpark Python 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 (DB.SCHEMA.TABLE).')\n .requiredOption('--source <path>', 'Source path for the read (stage path or S3 URI).')\n .option(\n '--runtime <ver>',\n 'Snowpark runtime version tag (e.g. snowpark-python-1.22).',\n 'snowpark-python-1.x',\n )\n .option('--merge-schema', 'Emit ENABLE_SCHEMA_EVOLUTION comment.', 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 Snowflake MERGE SQL for a given table and SCD strategy.')\n .requiredOption('--table <fqn>', 'Target table FQN (DB.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 .sql file 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: deploy.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 sql = deploy.emitScdMerge(strategy, {\n targetFqn: opts.table,\n sourceFqn: `STG.STG_${sanitizeFileStem(opts.table).toUpperCase()}`,\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(path.join(path.resolve(opts.out), `scd_${stem}.sql`), sql, 'utf8');\n } else {\n process.stdout.write(sql + '\\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 snowpark).', 'snowpark')\n .option('--schema <catalog.schema>', 'Target catalog.schema prefix (default DW.PUBLIC).')\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 ?? 'snowpark') 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 ?? 'DW.PUBLIC',\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/** `DW.PUBLIC.FACT_SALES` → `dw_public_fact_sales` */\nfunction sanitizeFileStem(fqn: string): string {\n return fqn\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '_')\n .replace(/^_|_$/g, '');\n}\n","/**\n * `sdt exec <file.sql> --profiles <list>` — AUTH.3.\n *\n * Runs a SQL script on one or more connection profiles in parallel and\n * prints a merged report. Guarded against any profile whose name matches\n * the word \"prod\" or \"production\" (case-insensitive) unless `--yes` is\n * passed.\n *\n * Mirrors `Databricks/packages/cli/src/commands/exec.ts`.\n */\nimport { Command } from 'commander';\nimport { promises as fs } from 'node:fs';\nimport { getProfile, SnowflakeConnection } from '@sdt-tools/core/connection';\nimport { queryExecution } from '@sdt-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 Snowflake connection layer:\n * 1. Resolve the named profile (`~/.sdt/profiles.json`).\n * 2. Open a connection; on failure surface the underlying SDK error.\n * 3. Split the SQL via the shared `queryExecution.splitStatements`\n * (string-/comment-/dollar-quote-aware) and run each statement\n * sequentially through `SnowflakeConnection.query`. We do NOT\n * `failFast` so a script 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 = new SnowflakeConnection(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 toolName: 'sdt',\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 * `sdt 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 `Databricks/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 '@sdt-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 // Scan profiles directory for known profile files\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>/.sdt/cache/<profile>/catalog.msgpack`\n * written by `sdt catalog refresh` / `sdt 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 (database, 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 `database.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.databases.length === 0) {\n throw new Error(\n `No catalog cache for profile \"${profile}\" at ${cache.path}. ` +\n `Run \\`sdt catalog refresh --connection ${profile} --root ${root}\\` ` +\n `or \\`sdt 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 db of snapshot.databases) {\n for (const schema of db.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.database}.${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(), '.sdt', 'connections'),\n )\n .option(\n '--root <dir>',\n 'Project / cache root containing the .sdt/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 \\`sdt 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 * `sdt query-log` — AUTH.5 local query log CLI.\n *\n * Subcommands:\n * sdt query-log list [--profile <p>] [--limit N] [--format text|json]\n * sdt query-log show <id> [--format text|json|sql]\n * sdt query-log add <sql> --profile <p> [--status success|error] [--store <path>]\n * sdt query-log clear [--profile <p>] [--yes]\n *\n * The log is stored at `~/.sdt/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 `Databricks/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 '@sdt-tools/core';\n\nconst DEFAULT_STORE = path.join(os.homedir(), '.sdt', '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 * `sdt savings` — display estimated AI token savings accumulated by using\n * deterministic SDT surfaces instead of LLM calls.\n *\n * DSC.8: token-savings counter CLI.\n *\n * $ sdt savings\n * $ sdt savings --format json\n * $ sdt savings --top 5\n * $ sdt savings --reset\n *\n * Persistence: `~/.sdt/token-savings.json` (override with `--store <path>`).\n * The substrate (`@sdt-tools/core TokenSavingsCounter`) is pure in-memory; this\n * file is the disk-I/O boundary.\n *\n * Mirrors `Databricks/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 '@sdt-tools/core';\nimport chalk from 'chalk';\n\nconst DEFAULT_STORE = path.join(os.homedir(), '.sdt', '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 SDT 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 ' SDT 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(' sdt savings --reset · sdt savings --format json\\n'),\n );\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 @sdt-tools/core/errorReport (capture substrate + consent + transport)\n */\nimport { createInterface } from 'node:readline';\n// Subpath import, NOT the `@sdt-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 '@sdt-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: 'sdt',\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 SDT 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/** SDT 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 `│ SDT ${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: sdt feedback \"<what happened>\" │',\n '└─────────────────────────────────────────────────────────┘',\n ];\n for (const line of lines) logger.info(line);\n}\n\nasync function promptFirstRunConsent(): Promise<boolean> {\n logger.info('SDT 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 * `sdt` command entry point.\n *\n * Subcommand modules are loaded LAZILY: only the requested subcommand's\n * module (and its `@sdt-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: `sdt <known-cmd> ...` skips ~80 command-module loads\n * and their per-module `@sdt-tools/core/...` imports. Reasoning in\n * docs/BACKLOG.md COLD cluster + the 200 ms cold-start standing bar.\n */\nimport { Command } from 'commander';\nimport { logger } from './util/logger.js';\nimport { FeatureAdvisor, SDT_HINT_RULES } from '@sdt-tools/core/discovery';\n// Subpath imports, NOT the `@sdt-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 '@sdt-tools/core/outputStyle';\nimport * as featuresNs from '@sdt-tools/core/features';\nimport chalk from 'chalk';\n\n// Cold-start timestamp for `sdt 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 { __SDT_START_NS__?: bigint }).__SDT_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 `sdt <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 init: async () => (await import('./commands/init.js')).initCommand(),\n extract: async () => (await import('./commands/extract.js')).extractCommand(),\n build: async () => (await import('./commands/build.js')).buildCommand(),\n publish: async () => (await import('./commands/publish.js')).publishCommand(),\n compare: async () => (await import('./commands/compare.js')).compareCommand(),\n drift: async () => (await import('./commands/drift.js')).driftCommand(),\n validate: async () => (await import('./commands/validate.js')).validateCommand(),\n connection: async () => (await import('./commands/connection.js')).connectionCommand(),\n refactor: async () => (await import('./commands/refactor.js')).refactorCommand(),\n import: async () => (await import('./commands/import.js')).importCommand(),\n format: async () => (await import('./commands/format.js')).formatCommand(),\n completion: async () => (await import('./commands/completion.js')).completionCommand(),\n telemetry: async () => (await import('./commands/telemetry.js')).telemetryCommand(),\n license: async () => (await import('./commands/license.js')).licenseCommand(),\n trial: async () => (await import('./commands/trial.js')).trialCommand(),\n pilot: async () => (await import('./commands/pilot.js')).pilotCommand(),\n suite: async () => (await import('./commands/suite.js')).suiteCommand(),\n docs: async () => (await import('./commands/docs.js')).docsCommand(),\n erd: async () => (await import('./commands/docs.js')).erdCommand(),\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 lint: async () => (await import('./commands/lint.js')).lintCommand(),\n features: async () => (await import('./commands/features.js')).featuresCommand(),\n hosts: async () => (await import('./commands/hosts.js')).hostsCommand(),\n 'install-hooks': async () => (await import('./commands/install-hooks.js')).installHooksCommand(),\n history: async () => (await import('./commands/history.js')).historyCommand(),\n 'audit-log': async () => (await import('./commands/audit-log.js')).auditLogCommand(),\n verify: async () => (await import('./commands/verify.js')).verifyCommand(),\n graph: async () => (await import('./commands/graph.js')).graphCommand(),\n script: async () => (await import('./commands/script.js')).scriptCommand(),\n revert: async () => (await import('./commands/revert.js')).revertCommand(),\n snapshot: async () => (await import('./commands/snapshot.js')).snapshotCommand(),\n seed: async () => (await import('./commands/seed.js')).seedCommand(),\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 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 export: async () => (await import('./commands/export.js')).exportCommand(),\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};\n\nasync function main(): Promise<void> {\n const program = new Command();\n program\n .name('sdt')\n .description('Snowflake Data Tools — declarative schema management for Snowflake.')\n .version('0.2.0', '-v, --version')\n .option(\n '--style <mode>',\n 'Output style: standard | audit | ci | review | terse. Also reads SDT_OUTPUT_STYLE env var.',\n outputStyle.resolveOutputStyle(),\n )\n .option('--explain-features', 'After each command, show related features from the catalog.');\n\n // Decide whether to load all commands or just the requested one. The\n // \"explicit known command\" path is the cold-start win — every other\n // path needs the full subcommand list registered so Commander can\n // render --help or emit the standard \"unknown command\" error.\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 (`sdt\n // 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 `sdt explain allowDropTable` for safety + path detail\n // without leaving the terminal. Mirrors the DDT-side footer.\n program.addHelpText('afterAll', () =>\n [\n '',\n 'Options catalog:',\n ' Every CLI flag and `.sdtproj` option has a searchable entry with safety',\n ' tier, default, related options, and an example. Look one up with:',\n ' sdt explain <name> # e.g. sdt explain allowDropTable',\n ' sdt explain <topic> # fuzzy: \"drop\", \"safety\", \"compare\"',\n '',\n 'Features catalog (locked + unlocked):',\n ' sdt features list # what ships in each tier',\n ' sdt features show <id>',\n '',\n 'Personalized suggestions:',\n ' sdt 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 SDT_NO_HINTS=1.\n const sdtAdvisor = new FeatureAdvisor('sdt', SDT_HINT_RULES);\n program.hook('postAction', (_thisCommand, actionCommand) => {\n // Only hint for direct sdt subcommands, not nested subcommands.\n if (actionCommand.parent !== program) return;\n const tip = sdtAdvisor.advise(actionCommand.name());\n if (tip) {\n console.log(chalk.dim(`\\n ✦ ${tip}`));\n console.log(chalk.dim(' sdt discover · sdt 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.SDT_FEATURE_CATALOG,\n cmdName,\n 3,\n 'sdt',\n );\n const hint = featuresNs.renderRelatedFeaturesHint(related, cmdName, 'sdt');\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 logger.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":";;;;;;;;;;;;;;;;;;AAIA,OAAO,WAAW;AAJlB,IAMa;AANb;AAAA;AAAA;AAMO,IAAM,SAAS;AAAA,MACpB,MAAM,CAAC,QAAgB,QAAQ,IAAI,GAAG;AAAA,MACtC,SAAS,CAAC,QAAgB,QAAQ,IAAI,MAAM,MAAM,QAAG,GAAG,GAAG;AAAA,MAC3D,MAAM,CAAC,QAAgB,QAAQ,KAAK,MAAM,OAAO,GAAG,GAAG,GAAG;AAAA,MAC1D,OAAO,CAAC,QAAgB,QAAQ,MAAM,MAAM,IAAI,QAAG,GAAG,GAAG;AAAA,MACzD,MAAM,CAAC,QAAgB,QAAQ,IAAI,MAAM,KAAK,QAAG,GAAG,GAAG;AAAA,MACvD,KAAK,CAAC,QAAgB,QAAQ,IAAI,MAAM,KAAK,GAAG,CAAC;AAAA,IACnD;AAAA;AAAA;;;ACbA;AAAA;AAAA;AAAA;AAAA,OAAO,UAAU;AACjB,SAAS,YAAY,UAAU;AAC/B,SAAS,eAAe;AACxB,SAAS,oBAAoB,mBAAmB;AAIzC,SAAS,cAAuB;AACrC,QAAM,MAAM,IAAI,QAAQ,MAAM;AAC9B,MACG,YAAY,wDAAwD,EACpE,OAAO,iBAAiB,gBAAgB,qBAAqB,EAC7D,OAAO,mBAAmB,8CAA8C,UAAU,EAClF,OAAO,mBAAmB,oDAAoD,EAC9E,OAAO,qBAAqB,yCAAyC,EACrE,OAAO,eAAe,mCAAmC,QAAQ,IAAI,CAAC,EACtE,OAAO,OAAO,SAAS;AACtB,UAAM,YAAY,OAAO,KAAK,KAAK;AACnC,QAAI,CAAC,CAAC,WAAW,YAAY,QAAQ,EAAE,SAAS,SAAS,GAAG;AAC1D,YAAM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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,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,CAAC,MAAM,SAAS,GAAG,EAAE;AAAA,EACvB,EACC;AAAA,IACC;AAAA,IACA;AAAA,IACA,CAAC,MAAM,SAA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I,KAAM,SAAQ,IAAIA,OAAM,IAAI,OAAO,IAAI,CAAC;AAAA,IAC9C;AAAA,EACF,CAAC;AAED,QAAM,QAAQ,WAAW,QAAQ,IAAI;AACvC;AAEA,KAAK,EAAE,MAAM,OAAO,QAAiB;AACnC,SAAO,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAC7D,UAAQ,WAAW;AAGnB,MAAI;AACF,UAAM,YAAY,MAAM;AACxB,UAAM,UAAU,iBAAiB,KAAK,OAAO;AAAA,EAC/C,QAAQ;AAAA,EAER;AACF,CAAC;","names":["project","path","fs","Command","profile","Command","fs","path","fs","Command","getProfile","SnowflakeConnection","pac","profile","schema","bodyReport","wrap","path","fs","Command","CompareEngine","LiveSource","getProfile","SnowflakeConnection","compileSlice","ai","safety","schema","profile","assessment","Command","path","readPac","CompareEngine","LiveSource","getProfile","SnowflakeConnection","loadProject","format","profile","pac","ModelSource","fs","path","Command","report","Command","getProfile","SnowflakeConnection","profile","fs","path","Command","Command","fs","path","Command","d","project","Command","Command","fs","homedir","path","Command","Command","license","Command","license","path","Command","licenseApi","fs","path","Command","loadProject","readPac","ai","outPath","path","Command","CompareEngine","PacSource","renderDocsReport","renderErdMarkdown","loadProject","parseProjectModel","readPac","loadModel","Command","ai","Command","safety","fs","path","Command","license","fs","path","Command","Command","licenseApi","license","Command","fs","existsSync","path","Command","fs","path","Command","getProfile","SnowflakeConnection","entries","profile","Command","writeFile","compare","Command","ai","fs","path","Command","compare","pac","project","loadModel","fs","path","Command","CompareEngine","PacSource","ProjectSource","ScriptGenerator","colorizeMigrationScript","mergeDeployOptions","loadProject","readPac","safety","format","header","fs","Command","getProfile","SnowflakeConnection","SnowflakeExecutor","profile","path","fs","Command","safety","getProfile","SnowflakeConnection","coreSplitStatements","profile","fs","path","Command","getProfile","SnowflakeConnection","SnowflakeExecutor","loadProject","profile","fs","path","Command","pac","project","readFile","writeFile","format","model","loadModel","focus","direction","fmt","payload","lineage","fs","path","Command","interop","pac","project","loadModel","fs","path","Command","ai","pac","project","loadModel","safety","format","fs","path","Command","pac","project","review","loadModel","emit","fs","path","Command","renderMarkdown","splitStatements","fs","path","Command","CompareEngine","PacSource","ProjectSource","safety","pac","project","review","loadModel","fs","path","Command","schema","fs","path","Command","pac","project","loadModel","fs","path","Command","project","testFramework","getProfile","SnowflakeConnection","profile","fs","path","Command","getProfile","SnowflakeConnection","profile","fs","path","Command","interop","pac","project","validateNs","loadModel","emit","fs","path","Command","pac","project","schema","loadModel","Command","format","renderMarkdown","fs","path","Command","ai","pac","project","loadModel","renderMarkdown","renderTable","emit","path","Command","loadProject","fs","path","execFile","promisify","Command","renderMarkdown","execFileP","canonical","fs","path","Command","getProfile","SnowflakeConnection","SnowflakeExecutor","profile","Command","CompareEngine","LiveSource","getProfile","SnowflakeConnection","execFile","promisify","fs","os","path","Command","CompareEngine","LiveSource","ScriptGenerator","assess","getProfile","SnowflakeConnection","totalChanges","execFileP","format","profile","fs","path","Command","CompareEngine","PacSource","emit","fs","path","Command","getProfile","SnowflakeConnection","format","profile","path","Command","approval","DEFAULT_ROOT","fs","path","Command","ai","readStdin","format","fs","Command","ai","fs","Command","ai","readStdin","splitFqn","Command","ai","readStdin","splitFqn","KINDS","fs","path","Command","pac","project","loadModel","renderMarkdown","renderTable","fs","Command","ai","readInput","fs","Command","catalog","pac","project","readStdin","profile","Command","catalog","Command","catalog","getProfile","SnowflakeConnection","profile","Command","fs","format","fs","path","Command","getProfile","SnowflakeConnection","fetchLiveRows","readRowsFile","format","fs","path","Command","ai","format","parseFqn","path","Command","compare","fs","fs","path","Command","compare","header","fs","path","Command","getProfile","SnowflakeConnection","profile","fs","path","Command","compare","header","join","homedir","Command","chalk","fs","path","homedir","Command","featuresApi","licenseApi","chalk","fs","path","Command","pac","project","loadModel","Command","path","Command","fs","path","Command","verifyCommand","fs","path","Command","fs","path","Command","loadProject","parseProjectModel","path","fs","Command","collectSqlFiles","path","fs","Command","fs","path","Command","fs","path","Command","fs","os","path","Command","Command","fs","path","Command","deploy","schema","Command","fs","getProfile","SnowflakeConnection","profile","result","Command","fs","os","path","catalog","renderText","profile","schema","Command","fs","os","path","loadStore","saveStore","DEFAULT_STORE","fs","os","path","Command","chalk","DEFAULT_STORE","counter","weeks","top","errorReport","Command","FeatureAdvisor","SDT_HINT_RULES","chalk"]}
1
+ {"version":3,"sources":["../src/cli.ts","../src/commandManifest.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * `sdt` command entry point.\n *\n * Subcommand modules are loaded LAZILY: only the requested subcommand's\n * module (and its `@sdt-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: `sdt <known-cmd> ...` skips ~80 command-module loads\n * and their per-module `@sdt-tools/core/...` imports. Reasoning in\n * docs/BACKLOG.md COLD cluster + the 200 ms cold-start standing bar.\n */\nimport { Command, Help } from 'commander';\nimport { logger } from './util/logger.js';\n// RH4.2 — core modules are imported LAZILY (dynamic `import()` at the use\n// site), NOT eagerly at module top. The eager subpath imports of\n// `@sdt-tools/core/{discovery,features,outputStyle}` each statically pulled\n// their whole barrel subtree into the startup chunk, which Node parsed +\n// evaluated on every invocation — including the `--version` / `--help`\n// fast paths that never touch them. Deferring them lets tsup code-split\n// those subtrees out of the eager chunk so cold start pays only Node\n// bootstrap + commander + the requested command. `import type` is free\n// (erased at compile), so types stay top-level. The barrel (`@sdt-tools/core`)\n// is still never imported — subpath / dynamic only (RH3.3 pin).\nimport type { OutputStyle } from '@sdt-tools/core/outputStyle';\nimport { COMMAND_MANIFEST } from './commandManifest.js';\nimport chalk from 'chalk';\n\nconst VALID_OUTPUT_STYLES = new Set<OutputStyle>(['standard', 'audit', 'ci', 'review', 'terse']);\n\n/**\n * Resolve the default `--style` value without eagerly loading the\n * `@sdt-tools/core/outputStyle` module on the cold-start path. Mirrors\n * `resolveOutputStyle()` exactly (env var → default 'standard'); the flag\n * value is not yet known here (commander resolves it after parse), so this\n * only folds in `SDT_OUTPUT_STYLE`. Kept in lockstep with\n * core/outputStyle/style.ts `resolveOutputStyle`.\n */\nfunction defaultOutputStyle(): OutputStyle {\n const env = process.env['SDT_OUTPUT_STYLE'];\n if (env && VALID_OUTPUT_STYLES.has(env as OutputStyle)) return env as OutputStyle;\n return 'standard';\n}\n\nconst CLI_VERSION = '0.2.6';\n\n// Cold-start timestamp for `sdt 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 { __SDT_START_NS__?: bigint }).__SDT_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 `sdt <name>` command, add its entry here. Aliases (`erd`)\n// can re-use the same module export with a different factory name.\nexport const COMMAND_LOADERS: Record<string, () => Promise<Command>> = {\n init: async () => (await import('./commands/init.js')).initCommand(),\n extract: async () => (await import('./commands/extract.js')).extractCommand(),\n build: async () => (await import('./commands/build.js')).buildCommand(),\n publish: async () => (await import('./commands/publish.js')).publishCommand(),\n compare: async () => (await import('./commands/compare.js')).compareCommand(),\n drift: async () => (await import('./commands/drift.js')).driftCommand(),\n validate: async () => (await import('./commands/validate.js')).validateCommand(),\n connection: async () => (await import('./commands/connection.js')).connectionCommand(),\n refactor: async () => (await import('./commands/refactor.js')).refactorCommand(),\n import: async () => (await import('./commands/import.js')).importCommand(),\n 'import-script': async () => (await import('./commands/import-script.js')).importScriptCommand(),\n format: async () => (await import('./commands/format.js')).formatCommand(),\n completion: async () => (await import('./commands/completion.js')).completionCommand(),\n telemetry: async () => (await import('./commands/telemetry.js')).telemetryCommand(),\n license: async () => (await import('./commands/license.js')).licenseCommand(),\n trial: async () => (await import('./commands/trial.js')).trialCommand(),\n pilot: async () => (await import('./commands/pilot.js')).pilotCommand(),\n suite: async () => (await import('./commands/suite.js')).suiteCommand(),\n docs: async () => (await import('./commands/docs.js')).docsCommand(),\n erd: async () => (await import('./commands/docs.js')).erdCommand(),\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 lint: async () => (await import('./commands/lint.js')).lintCommand(),\n features: async () => (await import('./commands/features.js')).featuresCommand(),\n hosts: async () => (await import('./commands/hosts.js')).hostsCommand(),\n 'install-hooks': async () => (await import('./commands/install-hooks.js')).installHooksCommand(),\n history: async () => (await import('./commands/history.js')).historyCommand(),\n 'audit-log': async () => (await import('./commands/audit-log.js')).auditLogCommand(),\n verify: async () => (await import('./commands/verify.js')).verifyCommand(),\n graph: async () => (await import('./commands/graph.js')).graphCommand(),\n script: async () => (await import('./commands/script.js')).scriptCommand(),\n revert: async () => (await import('./commands/revert.js')).revertCommand(),\n snapshot: async () => (await import('./commands/snapshot.js')).snapshotCommand(),\n seed: async () => (await import('./commands/seed.js')).seedCommand(),\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 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 export: async () => (await import('./commands/export.js')).exportCommand(),\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};\n\nasync function main(): Promise<void> {\n // RH4.2 cold-start fast path: `sdt -v` / `sdt --version` is the canonical\n // cold-start benchmark and must not load any command chunk. With code\n // splitting (tsup `splitting: true`) the no-arg / `--help` / `--version`\n // path otherwise loads ALL ~85 command chunks (separate files) so\n // commander can render the full subcommand list — dozens of disk reads\n // that dominate wall-clock on Windows. `--version` only needs the\n // version string, so short-circuit before building the program. Mirrors\n // commander's own `--version` output (bare version line) exactly.\n const firstArg = process.argv[2];\n if (firstArg === '--version' || firstArg === '-v') {\n process.stdout.write(CLI_VERSION + '\\n');\n return;\n }\n\n const program = new Command();\n program\n .name('sdt')\n .description('Snowflake Data Tools — declarative schema management for Snowflake.')\n .version(CLI_VERSION, '-v, --version')\n .option(\n '--style <mode>',\n 'Output style: standard | audit | ci | review | terse. Also reads SDT_OUTPUT_STYLE env var.',\n defaultOutputStyle(),\n )\n .option('--explain-features', 'After each command, show related features from the catalog.');\n\n // Decide whether to load all commands or just the requested one. The\n // \"explicit known command\" path is the cold-start win — every other\n // path needs the full subcommand list registered so Commander can\n // render --help or emit the standard \"unknown command\" error.\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 // RH4.7 — help / no-arg / unknown-command path. Register STUB\n // subcommands (name + description) from the static manifest instead of\n // loading all ~85 command modules. Commander renders the subcommand\n // list + the standard \"unknown command\" error from these stubs with\n // zero command-module imports. The stub carries no options/arguments,\n // so its rendered term would be just the bare name; override\n // `subcommandTerm` to emit the manifest's exact term (e.g.\n // `compare [options] <source> <target>`) so the --help columns are\n // byte-identical to the load-everything path. Per-command help\n // (`sdt <cmd> --help`) still loads the real module via the\n // explicit-loader path above, so argument/option detail is unaffected.\n for (const [name, entry] of Object.entries(COMMAND_MANIFEST)) {\n program.command(name).description(entry.description);\n }\n const defaultHelp = new Help();\n program.configureHelp({\n // Manifest commands render their exact term; the implicit `help`\n // subcommand (and anything else not in the manifest) falls back to\n // commander's own term so `help [command]` stays intact.\n subcommandTerm: (cmd) =>\n COMMAND_MANIFEST[cmd.name()]?.term ?? defaultHelp.subcommandTerm(cmd),\n });\n }\n\n // Global help footer — surfaces the searchable options catalog (`sdt\n // 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 `sdt explain allowDropTable` for safety + path detail\n // without leaving the terminal. Mirrors the DDT-side footer.\n program.addHelpText('afterAll', () =>\n [\n '',\n 'Options catalog:',\n ' Every CLI flag and `.sdtproj` option has a searchable entry with safety',\n ' tier, default, related options, and an example. Look one up with:',\n ' sdt explain <name> # e.g. sdt explain allowDropTable',\n ' sdt explain <topic> # fuzzy: \"drop\", \"safety\", \"compare\"',\n '',\n 'Features catalog (locked + unlocked):',\n ' sdt features list # what ships in each tier',\n ' sdt features show <id>',\n '',\n 'Personalized suggestions:',\n ' sdt 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(CLI_VERSION);\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 SDT_NO_HINTS=1.\n // RH4.2 — the FeatureAdvisor + hint rules and the features catalog are\n // imported LAZILY inside the hook so the cold-start path (which never\n // runs an action hook for `--version` / `--help`) pays nothing for them.\n program.hook('postAction', async (_thisCommand, actionCommand) => {\n // Only hint for direct sdt subcommands, not nested subcommands.\n if (actionCommand.parent !== program) return;\n const { FeatureAdvisor, SDT_HINT_RULES } = await import('@sdt-tools/core/discovery');\n const sdtAdvisor = new FeatureAdvisor('sdt', SDT_HINT_RULES);\n const tip = sdtAdvisor.advise(actionCommand.name());\n if (tip) {\n console.log(chalk.dim(`\\n ✦ ${tip}`));\n console.log(chalk.dim(' sdt discover · sdt 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 featuresNs = await import('@sdt-tools/core/features');\n const related = featuresNs.pickRelatedFeatures(\n featuresNs.SDT_FEATURE_CATALOG,\n cmdName,\n 3,\n 'sdt',\n );\n const hint = featuresNs.renderRelatedFeaturesHint(related, cmdName, 'sdt');\n if (hint) console.log(chalk.dim('\\n' + hint));\n }\n });\n\n await program.parseAsync(process.argv);\n}\n\n// Only auto-run when invoked as the CLI entry point, not when imported by\n// a test harness (the COMMAND_LOADERS / COMMAND_MANIFEST anti-drift test\n// imports this module to introspect the registry without dispatching).\nif (process.env['SDT_CLI_NO_MAIN'] !== '1') {\n main().catch(async (err: unknown) => {\n logger.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, CLI_VERSION);\n } catch {\n // Error reporting must never mask the original failure.\n }\n });\n}\n","/**\n * Static command manifest — subcommand name → { term, description }.\n *\n * RH4.7: the `--help` / no-arg / unknown-command paths render the full\n * subcommand list. Building that list by loading every entry in\n * `COMMAND_LOADERS` forces ~85 lazy command chunks (and their\n * `@sdt-tools/core/...` dependency chains) off disk on a path that never\n * executes a command — the dominant cost of `sdt --help` cold start.\n *\n * Instead, the help/error paths register STUB subcommands from this\n * manifest and render the subcommand list from it, so Commander produces a\n * byte-identical subcommand list + usage error without importing a single\n * command module. The real module is loaded only when a known command is\n * actually dispatched (see `cli.ts`).\n *\n * - `term` — the exact left-column term Commander renders for the\n * command in the parent --help list (name + ` [options]`\n * when the command registers any option + the\n * human-readable positional-argument signature). Used to\n * override `subcommandTerm` so the help columns line up\n * identically to the load-everything path.\n * - `description` — the one-line string the command module passes to\n * commander's `.description(...)`.\n *\n * `commandManifest.test.ts` dynamically loads every `COMMAND_LOADERS` entry\n * and asserts both `term` and `description` match what the real module\n * registers, plus that the key set + order are identical — so any drift (a\n * changed description, a new/removed option or argument, a new command\n * without a manifest row, a stale row) fails the test rather than silently\n * rotting the help text.\n *\n * Key order is kept aligned with `COMMAND_LOADERS` in `cli.ts` so the\n * rendered `--help` subcommand ordering is unchanged.\n */\nexport interface CommandManifestEntry {\n /** Exact Commander subcommand term for the parent --help list. */\n readonly term: string;\n /** One-line description (must equal the module's `.description(...)`). */\n readonly description: string;\n}\n\nexport const COMMAND_MANIFEST: Record<string, CommandManifestEntry> = {\n init: {\n term: 'init [options]',\n description: 'Initialize a new SDT project in the current directory.',\n },\n extract: {\n term: 'extract [options]',\n description: 'Extract a Snowflake account/database/schema into a project layout.',\n },\n build: { term: 'build [options]', description: 'Build a .sdtpac from a .sdtproj project.' },\n publish: {\n term: 'publish [options]',\n description:\n 'Compare a .sdtpac (the desired state) to a live Snowflake target and apply (or dry-run) the migration. Shared form with `ddt publish`: `--source <desired> --connection <live-target>`.',\n },\n compare: {\n term: 'compare [options] [source] [target]',\n description:\n 'Compare two schemas. Sources may be .sdtproj, .sdtpac, or snowflake://<profile>[/db[/schema]].',\n },\n drift: {\n term: 'drift [options]',\n description:\n 'Check whether a live Snowflake target has drifted from the project pac or a dbt manifest.',\n },\n validate: {\n term: 'validate [options]',\n description:\n 'Validate a .sdtproj — schema check; optionally resolve every object reference (--references).',\n },\n connection: { term: 'connection', description: 'Manage Snowflake connection profiles.' },\n refactor: {\n term: 'refactor',\n description: 'Record refactor operations (renames, moves) so compare emits ALTER … RENAME.',\n },\n import: {\n term: 'import [options]',\n description: 'Convert artifacts from other tools into an SDT project.',\n },\n 'import-script': {\n term: 'import-script [options]',\n description:\n 'Parse a SQL script and write each DDL statement into the .sdtproj tree under its canonical folder.',\n },\n format: {\n term: 'format [options] [files...]',\n description:\n 'Format SQL files using the tokenizer-based v2 engine (refuse-on-invalid, idempotent, token-faithful).',\n },\n completion: {\n term: 'completion <shell>',\n description: 'Print shell completion script (bash, zsh, fish, powershell).',\n },\n telemetry: {\n term: 'telemetry',\n description: 'Control opt-in usage telemetry and automatic error reporting.',\n },\n license: {\n term: 'license',\n description: 'Manage the SDT license key (open-core, offline, warn-mode in v0.1).',\n },\n trial: { term: 'trial', description: 'Manage the SDT 30-day Pro trial (no account required).' },\n pilot: {\n term: 'pilot',\n description: 'Join or check the SDT pilot program (90-day Pro access for early adopters).',\n },\n suite: {\n term: 'suite',\n description: 'Manage a .sdtsuite — a collection of .sdtproj projects deploying together.',\n },\n docs: {\n term: 'docs [options]',\n description: 'Generate HTML schema docs from a .sdtproj or .sdtpac.',\n },\n erd: {\n term: 'erd [options]',\n description:\n 'Generate an ER diagram (Mermaid Markdown or interactive 3D HTML) from a .sdtproj or .sdtpac.',\n },\n mcp: {\n term: 'mcp',\n description:\n 'Start the SDT Model Context Protocol server on stdio (for Claude / Cursor / agents).',\n },\n ai: { term: 'ai', description: 'Configure and test the AI provider adapter (BYO key).' },\n explain: {\n term: 'explain [options] [query...]',\n description:\n 'Search the options catalog. Explains what an option does, when to use it, and what it pairs with.',\n },\n feedback: {\n term: 'feedback [options] <message...>',\n description: 'Send a feedback / bug / feature-request ticket to the SDT team.',\n },\n lint: {\n term: 'lint [options]',\n description:\n 'Lint a SQL script for risky deploy patterns. Exits non-zero on any ERROR-severity finding.',\n },\n features: {\n term: 'features',\n description:\n 'Browse SDT features. Free users see paid features too — with copy explaining what each one does and how to unlock it.',\n },\n hosts: {\n term: 'hosts',\n description:\n 'Browse every host SDT plugs into — CLI, VS Code, MCP agents, GitHub Actions, dbt, Airflow, etc. Shows supported versions and the host-specific tailoring notes.',\n },\n 'install-hooks': {\n term: 'install-hooks [options]',\n description:\n 'Install a git pre-commit hook that runs `sdt validate` + `sdt format --check` before each commit.',\n },\n history: {\n term: 'history [options]',\n description:\n 'List deploy manifests (default) or query the live Snowflake QUERY_HISTORY views via --last/--query/--verify.',\n },\n 'audit-log': {\n term: 'audit-log',\n description:\n 'Export deploy history to enterprise audit sinks (file / syslog / Splunk HEC / Datadog Logs).',\n },\n verify: {\n term: 'verify [options]',\n description: 'Recompute checksums on a .sdtpac and confirm every object matches the manifest.',\n },\n graph: {\n term: 'graph [options]',\n description: 'Build an object-dependency DAG and emit it as Mermaid or DOT.',\n },\n script: {\n term: 'script [options]',\n description:\n 'Generate a deploy SQL script for source → target. Always offline — does not touch the account.',\n },\n revert: {\n term: 'revert [options]',\n description:\n 'Replay a previous deploy manifest in reverse, executing reverseSql for each successful step.',\n },\n snapshot: {\n term: 'snapshot',\n description:\n 'Inspect / prune the pre-deploy snapshot registry written by `sdt publish --apply`.',\n },\n seed: {\n term: 'seed',\n description:\n 'Reference / dimension data seeds. Declare static rows next to DDL; engine generates MERGEs.',\n },\n lineage: {\n term: 'lineage [options]',\n description: 'Extract data-flow lineage from a .sdtproj, .sdtpac, or dbt manifest.json.',\n },\n diagnose: {\n term: 'diagnose [options]',\n description:\n 'Project-level health report: lint + lineage smells + object smells + cost smells, with reasoning.',\n },\n review: {\n term: 'review [options]',\n description:\n 'Senior-DBA-style health report (lint + lineage + smell + cost + safety, with reasoning).',\n },\n impact: {\n term: 'impact [options] <fqn>',\n description:\n 'Single-FQN blast-radius: who feeds it, who reads from it, what findings apply to it.',\n },\n 'cost-estimate': {\n term: 'cost-estimate [options]',\n description: 'Heuristic Snowflake-credit estimate for a generated migration script.',\n },\n 'pr-comment': {\n term: 'pr-comment [options]',\n description:\n 'Generate a Markdown PR comment from a source↔target compare (diff + safety + health).',\n },\n template: {\n term: 'template [options] <kind> <name>',\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 anonymize: {\n term: 'anonymize [options]',\n description: 'Generate MASKING POLICY DDL for PII columns detected in the project model.',\n },\n test: {\n term: 'test',\n description:\n 'Declarative tests (unique / not_null / accepted_values / relationships / expression) compiled from YAML to SQL.',\n },\n branch: {\n term: 'branch',\n description: 'PlanetScale-style branching via Snowflake zero-copy clone. create / drop / list.',\n },\n schema: {\n term: 'schema',\n description:\n 'Interop with third-party schema formats (DBML import/export; draw.io export). NOT a separate data modeler — SDT remains the canonical model.',\n },\n suggest: {\n term: 'suggest [options]',\n description:\n 'Suggest FK / PK / UK / composite-PK candidates with reasoning. Output is Markdown by default.',\n },\n safety: {\n term: 'safety',\n description:\n 'Inspect the safety-finding catalog. See `sdt safety list` and `sdt safety explain <code>`.',\n },\n pii: {\n term: 'pii',\n description:\n 'Detect PII columns + render Snowflake MASKING POLICY DDL. See `sdt pii scan` and `sdt pii mask`.',\n },\n bisect: {\n term: 'bisect [options] <fqn>',\n description: 'Find the commit where a specific FQN first changed in the project tree.',\n },\n changelog: {\n term: 'changelog [options]',\n description:\n 'Generate a Markdown CHANGELOG section from git commits between two refs (Conventional Commits parser).',\n },\n replay: {\n term: 'replay [options]',\n description:\n 'Re-execute forwardSql from one or more deploy manifests against a target Snowflake account.',\n },\n 'drift-gate': {\n term: 'drift-gate [options]',\n description:\n 'Refuse-on-drift CI gate across multiple replica Snowflake accounts. Compares replicas against a primary.',\n },\n promote: {\n term: 'promote [options]',\n description:\n 'Branch-per-env deploy: compare live source→target, optionally open a PR with the deploy bundle.',\n },\n 'data-fit': {\n term: 'data-fit [options]',\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 'data-compare': {\n term: 'data-compare [options]',\n description:\n 'Row-level data compare: diff two tables by primary key and emit an INSERT/UPDATE/DELETE script that converts target into source. Source/target rows read from JSON files in v1.',\n },\n approval: {\n term: 'approval',\n description: 'Record / list / verify multi-approver gate tokens for prod deploys.',\n },\n 'advise-tests': {\n term: 'advise-tests [options]',\n description:\n 'PR-time AI regression-test advisor. Walks the SDT feature catalog, flags features whose surfaces match the changed files, and recommends 1–8 tests to add alongside the diff.',\n },\n 'safer-alternative': {\n term: 'safer-alternative [options]',\n description:\n 'AI-assist: propose a safer DDL alternative for a safety finding. Requires a configured AI provider (sdt ai status).',\n },\n sketch: {\n term: 'sketch [options] <kind>',\n description:\n 'AI-assist: scaffold idiomatic Snowflake DDL from a prose description. Output always carries a REVIEW BEFORE DEPLOY header.',\n },\n design: {\n term: 'design',\n description:\n 'AI-assist: generative schema-design scaffolds. Output always carries a REVIEW BEFORE RUNNING header.',\n },\n optimize: {\n term: 'optimize [options]',\n description:\n 'Surface ranked optimization recommendations (clustering, narrowing, missing PKs, dynamic-table lag).',\n },\n 'rollback-suggest': {\n term: 'rollback-suggest [options]',\n description:\n 'AI-assist: propose a reverse SQL for a forward DDL when the deterministic plan-to-steps bridge could not invert it. Output always carries a REVIEW BEFORE APPLY header. Standalone — not auto-wired into `revert`.',\n },\n 'compare-profiles': {\n term: 'compare-profiles',\n description: 'Manage saved compare profiles (.sdt/compare-profiles.json).',\n },\n explorer: {\n term: 'explorer [options]',\n description:\n 'ASCII tree dump of the cached catalog for a connection. Run `sdt catalog refresh` first to populate.',\n },\n catalog: {\n term: 'catalog',\n description:\n 'Manage the per-connection catalog cache used by the Object Explorer + EE2 intellisense.',\n },\n 'xcompare-ir': {\n term: 'xcompare-ir [options]',\n description:\n 'Cross-platform IR compare (Snowflake ↔ Databricks). Maps source IRs through XPM-Deep substrate; emits tier-gated safety assessment. IR-level only (live-warehouse compare is a follow-up).',\n },\n profile: {\n term: 'profile [options] <fqn>',\n description:\n 'Compute per-column profile statistics (nulls, distinct, min/max, top values) for a table. Rows are read from a JSON file in v1 (live-warehouse executeRows wiring is a documented follow-up).',\n },\n 'suggest-constraints': {\n term: 'suggest-constraints [options] <fqn>',\n description:\n 'Suggest PK/UK/FK/CHECK candidates for a profiled table. Reads a TableProfile JSON (from `sdt profile`) and emits suggestions with confidence tiers + rationale.',\n },\n export: {\n term: 'export',\n description: 'Export an SDT project to another format (DCM, etc.). v1 supports `dcm` only.',\n },\n purge: {\n term: 'purge [options]',\n description:\n 'Generate a DROP script for every object in the project (bulk teardown). Requires --confirm-production. Honours all per-type drop gates — relax with --allow-* flags.',\n },\n preview: {\n term: 'preview [options] <fqn>',\n description:\n 'Preview rows from a table (SELECT * FROM <fqn> LIMIT <n>). Read-only — requires a connection profile.',\n },\n refresh: {\n term: 'refresh [options]',\n description:\n 'Generate a REFRESH script for the dynamic tables + tasks in the project. Operator runs the output script explicitly.',\n },\n discover: {\n term: 'discover [options]',\n description: 'Show personalized feature suggestions based on your usage history.',\n },\n find: {\n term: 'find [options] <query...>',\n description: 'Search SDT features by keyword — find what you want to do.',\n },\n 'scan-secrets': {\n term: 'scan-secrets [options]',\n description: 'Scan a project or pac for hardcoded credentials in DDL bodies.',\n },\n 'error-lookup': {\n term: 'error-lookup [options]',\n description: 'Look up a failure in the known-error catalog by code, fingerprint, or message.',\n },\n 'deploy-status': {\n term: 'deploy-status [options] [deployId]',\n description: 'Show or list resumable deploy checkpoints written by `sdt publish`.',\n },\n 'approval-chain': {\n term: 'approval-chain',\n description: 'Signed M-of-N approval workflow (DSR.8).',\n },\n standards: {\n term: 'standards',\n description: 'Team SQL standards — init, check, fix, and explain.',\n },\n perf: {\n term: 'perf',\n description: 'CLI performance diagnostics (cold-start audit, hot-path profiling).',\n },\n 'migrate-platform': {\n term: 'migrate-platform [options] <path>',\n description:\n 'Translate Snowflake SQL files to another platform dialect. v1: --to databricks. Reads .sql files from <path> (file or directory).',\n },\n migrate: {\n term: 'migrate',\n description: 'Migrate from another tool to SDT (`from-dbt` subcommand only in v1).',\n },\n backlog: {\n term: 'backlog',\n description: 'Local-compute backlog tooling. Pure parse + score; no warehouse contact.',\n },\n watch: {\n term: 'watch',\n description:\n 'Platform-feature drift detector. Diffs release-notes markdown against a cached snapshot.',\n },\n bookmarks: {\n term: 'bookmarks [options]',\n description: 'Save fast-access pointers to queries, files, or named sections.',\n },\n snippets: {\n term: 'snippets',\n description: 'Browse the built-in SQL snippet catalog (SCD, star schema, data quality).',\n },\n generate: {\n term: 'generate',\n description: 'Code generation: ingest notebooks, SCD merge scripts, star-schema pipelines.',\n },\n exec: {\n term: 'exec [options] <file>',\n description: 'Run a SQL script on one or more connection profiles in parallel.',\n },\n search: {\n term: 'search [options] <pattern>',\n description: 'Find objects matching a name pattern across one or more connection profiles.',\n },\n 'query-log': {\n term: 'query-log',\n description: 'Browse and manage the local query log from the EE3 query window (AUTH.5).',\n },\n savings: {\n term: 'savings [options]',\n description: 'Show estimated AI token savings from using deterministic SDT surfaces.',\n },\n};\n"],"mappings":";;;;;;;AAcA,SAAS,SAAS,YAAY;;;AC2BvB,IAAM,mBAAyD;A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