sdd-layer 0.18.3

Spec-Driven Development CLI and agent harness
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
'use strict'

const os = require('os')
const path = require('path')
const fs = require('fs')
const { execSync, spawnSync } = require('child_process')
const https = require('https')
const http = require('http')

// ─── helpers ─────────────────────────────────────────────────────────────────

function run(cmd, opts = {}) {
  return spawnSync(cmd, { shell: true, stdio: 'inherit', ...opts })
}

function runCapture(cmd, opts = {}) {
  try {
    return execSync(cmd, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], ...opts }).trim()
  } catch {
    return null
  }
}

function httpGet(url, headers = {}) {
  return new Promise((resolve, reject) => {
    const lib = url.startsWith('https') ? https : http
    lib.get(url, { headers }, (res) => {
      let data = ''
      res.on('data', (chunk) => (data += chunk))
      res.on('end', () => resolve({ status: res.statusCode, body: data }))
    }).on('error', reject)
  })
}

function httpPost(url, body, headers = {}) {
  return new Promise((resolve, reject) => {
    const lib = url.startsWith('https') ? https : http
    const payload = JSON.stringify(body)
    const urlObj = new URL(url)
    const opts = {
      hostname: urlObj.hostname,
      path: urlObj.pathname + urlObj.search,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(payload),
        ...headers,
      },
    }
    const req = lib.request(opts, (res) => {
      let data = ''
      res.on('data', (chunk) => (data += chunk))
      res.on('end', () => resolve({ status: res.statusCode, body: data }))
    })
    req.on('error', reject)
    req.write(payload)
    req.end()
  })
}

// ─── Node version check ───────────────────────────────────────────────────────

function checkNodeVersion() {
  const [major] = process.versions.node.split('.').map(Number)
  if (major < 20) {
    console.error(`  Node.js >= 20 required. Current: ${process.version}`)
    process.exit(1)
  }
  console.log(`  Node.js ${process.version}`)
}

// ─── npm install + build ──────────────────────────────────────────────────────

function npmInstallAndBuild() {
  const botDir = __dirname
  console.log('\n📦  Running npm install...')
  const r1 = run('npm install', { cwd: botDir })
  if (r1.status !== 0) { console.error('❌  npm install failed'); process.exit(1) }

  console.log('\n🔨  Running npm run build (tsc)...')
  const r2 = run('npm run build', { cwd: botDir })
  if (r2.status !== 0) { console.error('❌  npm run build failed'); process.exit(1) }
  console.log('✅  Build complete')
}

// ─── inquirer shim (dynamic require after npm install) ───────────────────────

async function getInquirer() {
  try {
    // inquirer v8 is CJS-compatible; v9+ is ESM-only — try both
    return require('inquirer')
  } catch {
    console.error('❌  inquirer not found. Make sure it is listed in bot/package.json dependencies.')
    process.exit(1)
  }
}

// ─── interactive config ───────────────────────────────────────────────────────

const MODEL_DEFAULTS = {
  anthropic: 'claude-sonnet-4-5',
  openai: 'gpt-4o',
  ollama: 'llama3',
}

async function promptConfig() {
  const inquirer = await getInquirer()

  const answers = await inquirer.prompt([
    {
      type: 'input',
      name: 'slackSessionName',
      message: 'Slack session name (e.g. cijira):',
      validate: (v) => v.trim().length > 0 || 'Required',
    },
    {
      type: 'password',
      name: 'slackBotToken',
      message: 'Slack Bot Token (xoxb-...):',
      validate: (v) => v.trim().startsWith('xoxb-') || 'Must start with xoxb-',
    },
    {
      type: 'password',
      name: 'slackAppToken',
      message: 'Slack App Token (xapp-...):',
      validate: (v) => v.trim().startsWith('xapp-') || 'Must start with xapp-',
    },
    {
      type: 'list',
      name: 'workTrackerProvider',
      message: 'Work tracker:',
      choices: ['jira', 'github'],
      default: 'jira',
    },
    {
      type: 'list',
      name: 'repoProvider',
      message: 'Repo provider:',
      choices: ['bitbucket', 'github', 'git'],
      default: (ans) => ans.workTrackerProvider === 'github' ? 'github' : 'bitbucket',
    },
    {
      type: 'input',
      name: 'jiraBaseUrl',
      message: 'Jira base URL (e.g. https://myorg.atlassian.net):',
      validate: (v) => v.trim().startsWith('http') || 'Must be a URL',
      when: (ans) => ans.workTrackerProvider === 'jira',
    },
    {
      type: 'input',
      name: 'jiraProjectKey',
      message: 'Jira project key:',
      validate: (v) => v.trim().length > 0 || 'Required',
      when: (ans) => ans.workTrackerProvider === 'jira',
    },
    {
      type: 'input',
      name: 'jiraBacklogColumn',
      message: 'Jira backlog column name:',
      default: 'Ideia/Backlog',
      when: (ans) => ans.workTrackerProvider === 'jira',
    },
    {
      type: 'password',
      name: 'jiraApiToken',
      message: 'Jira API token:',
      validate: (v) => v.trim().length > 0 || 'Required',
      when: (ans) => ans.workTrackerProvider === 'jira',
    },
    {
      type: 'input',
      name: 'jiraUserEmail',
      message: 'Jira user email:',
      validate: (v) => v.includes('@') || 'Must be an email',
      when: (ans) => ans.workTrackerProvider === 'jira',
    },
    {
      type: 'input',
      name: 'githubOwner',
      message: 'GitHub owner/org:',
      validate: (v) => v.trim().length > 0 || 'Required',
      when: (ans) => ans.workTrackerProvider === 'github' || ans.repoProvider === 'github',
    },
    {
      type: 'input',
      name: 'githubRepo',
      message: 'GitHub repo:',
      validate: (v) => v.trim().length > 0 || 'Required',
      when: (ans) => ans.workTrackerProvider === 'github' || ans.repoProvider === 'github',
    },
    {
      type: 'input',
      name: 'githubBaseBranch',
      message: 'GitHub base branch:',
      default: 'main',
      when: (ans) => ans.workTrackerProvider === 'github' || ans.repoProvider === 'github',
    },
    {
      type: 'input',
      name: 'githubTokenEnv',
      message: 'GitHub token env fallback:',
      default: 'GITHUB_TOKEN',
      when: (ans) => ans.workTrackerProvider === 'github' || ans.repoProvider === 'github',
    },
    {
      type: 'input',
      name: 'githubAppId',
      message: 'GitHub App ID (recommended; leave blank for token-only dev):',
      default: '',
      when: (ans) => ans.workTrackerProvider === 'github' || ans.repoProvider === 'github',
    },
    {
      type: 'input',
      name: 'githubInstallationId',
      message: 'GitHub App installation ID:',
      default: '',
      when: (ans) => Boolean(ans.githubAppId),
    },
    {
      type: 'input',
      name: 'githubPrivateKeyEnv',
      message: 'GitHub App private key env:',
      default: 'GITHUB_APP_PRIVATE_KEY',
      when: (ans) => Boolean(ans.githubAppId),
    },
    {
      type: 'input',
      name: 'githubProjectOwnerType',
      message: 'GitHub Projects v2 owner type:',
      default: 'organization',
      when: (ans) => ans.workTrackerProvider === 'github' || ans.repoProvider === 'github',
    },
    {
      type: 'input',
      name: 'githubProjectOwner',
      message: 'GitHub Projects v2 owner:',
      default: (ans) => ans.githubOwner,
      when: (ans) => ans.workTrackerProvider === 'github' || ans.repoProvider === 'github',
    },
    {
      type: 'input',
      name: 'githubProjectNumber',
      message: 'GitHub Projects v2 number (blank to skip):',
      default: '',
      when: (ans) => ans.workTrackerProvider === 'github' || ans.repoProvider === 'github',
    },
    {
      type: 'input',
      name: 'bitbucketWorkspace',
      message: 'Bitbucket workspace:',
      validate: (v) => v.trim().length > 0 || 'Required',
      when: (ans) => ans.repoProvider === 'bitbucket',
    },
    {
      type: 'input',
      name: 'bitbucketRepoSlug',
      message: 'Bitbucket repo slug:',
      validate: (v) => v.trim().length > 0 || 'Required',
      when: (ans) => ans.repoProvider === 'bitbucket',
    },
    {
      type: 'input',
      name: 'bitbucketBaseBranch',
      message: 'Bitbucket base branch:',
      default: 'homolog',
      when: (ans) => ans.repoProvider === 'bitbucket',
    },
    {
      type: 'password',
      name: 'bitbucketAppPassword',
      message: 'Bitbucket API token with scopes (bitbucket.org/account/settings/api-tokens — Repositories:RW, Pull requests:RW, Account:R):',
      validate: (v) => v.trim().length > 0 || 'Required',
      when: (ans) => ans.repoProvider === 'bitbucket',
    },
    {
      type: 'input',
      name: 'bitbucketUsername',
      message: 'Bitbucket email (email da conta, nao o username):',
      validate: (v) => v.trim().length > 0 || 'Required',
      when: (ans) => ans.repoProvider === 'bitbucket',
    },
    {
      type: 'list',
      name: 'llmProvider',
      message: 'LLM provider:',
      choices: ['anthropic', 'openai', 'ollama'],
    },
    {
      type: 'input',
      name: 'llmModel',
      message: 'Model name:',
      default: (ans) => MODEL_DEFAULTS[ans.llmProvider] || '',
    },
    {
      type: 'password',
      name: 'llmApiKey',
      message: 'API key (leave blank for ollama):',
      when: (ans) => ans.llmProvider !== 'ollama',
      default: '',
    },
  ])

  if (!answers.llmApiKey) answers.llmApiKey = ''
  return answers
}

// ─── connection validation ────────────────────────────────────────────────────

async function validateConnections(cfg) {
  const results = {}

  // Slack
  try {
    const r = await httpGet('https://slack.com/api/auth.test', {
      Authorization: `Bearer ${cfg.slackBotToken}`,
    })
    const body = JSON.parse(r.body)
    results.slack = body.ok === true
  } catch {
    results.slack = false
  }
  console.log(results.slack ? '✅  Slack' : '❌  Slack')

  // Jira
  if (cfg.workTrackerProvider === 'jira') try {
    const creds = Buffer.from(`${cfg.jiraUserEmail}:${cfg.jiraApiToken}`).toString('base64')
    const r = await httpGet(`${cfg.jiraBaseUrl.replace(/\/$/, '')}/rest/api/3/myself`, {
      Authorization: `Basic ${creds}`,
      Accept: 'application/json',
    })
    results.jira = r.status >= 200 && r.status < 300
  } catch {
    results.jira = false
  }
  if (cfg.workTrackerProvider === 'jira') console.log(results.jira ? '✅  Jira' : '❌  Jira')

  // GitHub
  if (cfg.workTrackerProvider === 'github' || cfg.repoProvider === 'github') try {
    const token = process.env[cfg.githubTokenEnv] || process.env.GH_TOKEN
    if (token) {
      const r = await httpGet(`https://api.github.com/repos/${cfg.githubOwner}/${cfg.githubRepo}`, {
        Authorization: `Bearer ${token}`,
        Accept: 'application/vnd.github+json',
        'X-GitHub-Api-Version': '2026-03-10',
        'User-Agent': 'sdd-layer',
      })
      results.github = r.status >= 200 && r.status < 300
    } else {
      results.github = Boolean(cfg.githubAppId && cfg.githubInstallationId && cfg.githubPrivateKeyEnv)
    }
  } catch {
    results.github = false
  }
  if (cfg.workTrackerProvider === 'github' || cfg.repoProvider === 'github') {
    console.log(results.github ? '✅  GitHub' : '❌  GitHub')
  }

  // Bitbucket
  if (cfg.repoProvider === 'bitbucket') try {
    const creds = Buffer.from(`${cfg.bitbucketUsername}:${cfg.bitbucketAppPassword}`).toString('base64')
    const r = await httpGet(`https://api.bitbucket.org/2.0/repositories/${cfg.bitbucketWorkspace}/${cfg.bitbucketRepoSlug}`, {
      Authorization: `Basic ${creds}`,
    })
    results.bitbucket = r.status >= 200 && r.status < 300
  } catch {
    results.bitbucket = false
  }
  if (cfg.repoProvider === 'bitbucket') console.log(results.bitbucket ? '✅  Bitbucket' : '❌  Bitbucket')

  // LLM
  try {
    if (cfg.llmProvider === 'anthropic') {
      const r = await httpPost(
        'https://api.anthropic.com/v1/messages',
        {
          model: cfg.llmModel,
          max_tokens: 8,
          messages: [{ role: 'user', content: 'ping' }],
        },
        {
          'x-api-key': cfg.llmApiKey,
          'anthropic-version': '2023-06-01',
        }
      )
      results.llm = r.status >= 200 && r.status < 300
    } else if (cfg.llmProvider === 'openai') {
      const r = await httpGet('https://api.openai.com/v1/models', {
        Authorization: `Bearer ${cfg.llmApiKey}`,
      })
      results.llm = r.status >= 200 && r.status < 300
    } else {
      // ollama — list models
      const r = await httpGet('http://localhost:11434/api/tags')
      results.llm = r.status >= 200 && r.status < 300
    }
  } catch {
    results.llm = false
  }
  console.log(results.llm ? `  LLM (${cfg.llmProvider})` : `  LLM (${cfg.llmProvider})`)

  return results
}

// ─── retry loop for failed services ──────────────────────────────────────────

async function retryFailedServices(cfg, results) {
  const inquirer = await getInquirer()
  const failed = Object.entries(results).filter(([, ok]) => !ok).map(([k]) => k)
  if (failed.length === 0) return cfg

  const { retry } = await inquirer.prompt([
    {
      type: 'confirm',
      name: 'retry',
      message: `Some connections failed (${failed.join(', ')}). Re-enter credentials?`,
      default: true,
    },
  ])
  if (!retry) return cfg

  const updatedCfg = { ...cfg }

  for (const service of failed) {
    if (service === 'slack') {
      const ans = await inquirer.prompt([
        { type: 'password', name: 'slackBotToken', message: 'Slack Bot Token:', validate: (v) => v.trim().length > 0 },
        { type: 'password', name: 'slackAppToken', message: 'Slack App Token:', validate: (v) => v.trim().length > 0 },
      ])
      Object.assign(updatedCfg, ans)
    } else if (service === 'jira') {
      const ans = await inquirer.prompt([
        { type: 'input', name: 'jiraBaseUrl', message: 'Jira base URL:', default: cfg.jiraBaseUrl },
        { type: 'password', name: 'jiraApiToken', message: 'Jira API token:' },
        { type: 'input', name: 'jiraUserEmail', message: 'Jira user email:', default: cfg.jiraUserEmail },
      ])
      Object.assign(updatedCfg, ans)
    } else if (service === 'github') {
      const ans = await inquirer.prompt([
        { type: 'input', name: 'githubTokenEnv', message: 'GitHub token env:', default: cfg.githubTokenEnv || 'GITHUB_TOKEN' },
        { type: 'input', name: 'githubAppId', message: 'GitHub App ID:', default: cfg.githubAppId || '' },
        { type: 'input', name: 'githubInstallationId', message: 'GitHub App installation ID:', default: cfg.githubInstallationId || '' },
        { type: 'input', name: 'githubPrivateKeyEnv', message: 'GitHub App private key env:', default: cfg.githubPrivateKeyEnv || 'GITHUB_APP_PRIVATE_KEY' },
      ])
      Object.assign(updatedCfg, ans)
    } else if (service === 'bitbucket') {
      const ans = await inquirer.prompt([
        { type: 'password', name: 'bitbucketAppPassword', message: 'Bitbucket API token with scopes:' },
        { type: 'input', name: 'bitbucketUsername', message: 'Bitbucket email (email da conta):', default: cfg.bitbucketUsername },
      ])
      Object.assign(updatedCfg, ans)
    } else if (service === 'llm') {
      const ans = await inquirer.prompt([
        { type: 'password', name: 'llmApiKey', message: 'LLM API key:' },
      ])
      Object.assign(updatedCfg, ans)
    }
  }

  console.log('\nRe-validating...')
  const newResults = await validateConnections(updatedCfg)
  return retryFailedServices(updatedCfg, newResults)
}

// ─── write config files ───────────────────────────────────────────────────────

function writeConfigFiles(cfg, projectRoot) {
  const botDir = path.join(projectRoot, '.sdd', 'bot')
  fs.mkdirSync(botDir, { recursive: true })
  fs.mkdirSync(path.join(botDir, 'versions'), { recursive: true })

const yaml = `# sdd-bot configuration  generated by install.js
# DO NOT commit this file.

slack:
  session_name: "${cfg.slackSessionName}"
  bot_token: "${cfg.slackBotToken}"
  app_token: "${cfg.slackAppToken}"

integrations:
  work_tracker: "${cfg.workTrackerProvider}"
  repo: "${cfg.repoProvider}"

${cfg.workTrackerProvider === 'jira' ? `\
jira:
  base_url: "${cfg.jiraBaseUrl}"
  project_key: "${cfg.jiraProjectKey}"
  backlog_column: "${cfg.jiraBacklogColumn}"
  api_token: "${cfg.jiraApiToken}"
  user: "${cfg.jiraUserEmail}"
` : ''}

${cfg.workTrackerProvider === 'github' || cfg.repoProvider === 'github' ? `\
github:
  owner: "${cfg.githubOwner}"
  repo: "${cfg.githubRepo}"
  base_branch: "${cfg.githubBaseBranch}"
  auth:
    token_env: "${cfg.githubTokenEnv || 'GITHUB_TOKEN'}"
    app_id: "${cfg.githubAppId || ''}"
    installation_id: "${cfg.githubInstallationId || ''}"
    private_key_env: "${cfg.githubPrivateKeyEnv || 'GITHUB_APP_PRIVATE_KEY'}"
  project:
    owner_type: "${cfg.githubProjectOwnerType || 'organization'}"
    owner: "${cfg.githubProjectOwner || cfg.githubOwner || ''}"
    number: ${cfg.githubProjectNumber ? Number(cfg.githubProjectNumber) : 0}
    field_mapping:
      status_field_id: ""
      todo_option_id: ""
      in_progress_option_id: ""
      done_option_id: ""
  webhook_secret_env: "GITHUB_WEBHOOK_SECRET"
  webhook:
    enabled: false
    port: 8787
    path: "/github/webhook"
  labels:
    - "sdd"
` : ''}

${cfg.repoProvider === 'bitbucket' ? `\
bitbucket:
  workspace: "${cfg.bitbucketWorkspace}"
  repo_slug: "${cfg.bitbucketRepoSlug}"
  base_branch: "${cfg.bitbucketBaseBranch}"
  app_password: "${cfg.bitbucketAppPassword}"
  user: "${cfg.bitbucketUsername}"
` : ''}

llm:
  provider: "${cfg.llmProvider}"
  model: "${cfg.llmModel}"
  api_key: "${cfg.llmApiKey}"

sdd:
  worktrees_root: "${projectRoot.replace(/\\/g, '\\\\')}\\\\.worktree"
`

  fs.writeFileSync(path.join(botDir, 'sdd-bot.config.yaml'), yaml, 'utf8')
  console.log('✅  Written .sdd/bot/sdd-bot.config.yaml')

  const sessionsPath = path.join(botDir, 'sessions.json')
  if (!fs.existsSync(sessionsPath)) {
    fs.writeFileSync(sessionsPath, '{}', 'utf8')
    console.log('✅  Created .sdd/bot/sessions.json')
  }
}

function writeEcosystemConfig(projectRoot) {
  const ecosystemPath = path.join(__dirname, 'ecosystem.config.js')
  const content = `module.exports = {
  apps: [{
    name: 'sdd-bot',
    script: './dist/index.js',
    cwd: __dirname,
    env: { NODE_ENV: 'production', SDD_BOT_ROOT: ${JSON.stringify(projectRoot)} },
    restart_delay: 5000,
    max_restarts: 10,
  }]
}
`
  fs.writeFileSync(ecosystemPath, content, 'utf8')
  console.log('✅  Written bot/ecosystem.config.js')
}

// Configura o remote 'origin' do projeto para autenticar com o API token do
// Bitbucket via o username estático x-bitbucket-api-token-auth — o método correto
// para Git over HTTPS (o e-mail da conta só funciona na REST API). Sem isso, o
// fetch/push do bot falha e a criação de worktree quebra. App passwords estão
// sendo descontinuados pelo Bitbucket, por isso usamos API token com scopes.
function configureGitRemote(cfg, projectRoot) {
  if (cfg.repoProvider === 'github') {
    const token = process.env[cfg.githubTokenEnv] || process.env.GH_TOKEN
    if (!token) {
      console.warn('⚠️   GitHub remote não configurado: token env ausente; GitHub App será usado apenas pela API')
      return
    }
    const url = `https://x-access-token:${token}@github.com/${cfg.githubOwner}/${cfg.githubRepo}.git`
    configureOriginUrl(projectRoot, url, 'GitHub')
    return
  }

  if (cfg.repoProvider !== 'bitbucket') return

  const token = cfg.bitbucketAppPassword
  const ws = cfg.bitbucketWorkspace
  const repo = cfg.bitbucketRepoSlug
  if (!token || !ws || !repo) {
    console.warn('⚠️   Dados do Bitbucket incompletos — pulei a configuração do remote git')
    return
  }
  const url = `https://x-bitbucket-api-token-auth:${token}@bitbucket.org/${ws}/${repo}.git`
  configureOriginUrl(projectRoot, url, 'Bitbucket')
}

function configureOriginUrl(projectRoot, url, label) {
  const hasOrigin = runCapture('git remote get-url origin', { cwd: projectRoot })
  const action = hasOrigin ? 'set-url' : 'add'
  // args como array (sem shell) — evita problemas de escaping do token (que tem
  // caracteres como '=' e '_') e não expõe o token na linha de comando do shell.
  const r = spawnSync('git', ['remote', action, 'origin', url], {
    cwd: projectRoot,
    stdio: 'pipe',
  })
  if (r.status === 0) {
    console.log(`  remote git origin configurado para ${label}`)
    const test = spawnSync('git', ['ls-remote', '--heads', 'origin'], {
      cwd: projectRoot,
      stdio: 'pipe',
      env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
    })
    console.log(
      test.status === 0
        ? '✅  autenticação git validada (fetch/push prontos para o bot)'
        : '⚠️   git ls-remote falhou — confirme o token e os scopes'
    )
  } else {
    console.warn('⚠️   não consegui configurar o remote git origin automaticamente')
  }
}

function updateGitignore(projectRoot) {
  const gitignorePath = path.join(projectRoot, '.gitignore')
  const entries = [
    '.sdd/bot/sdd-bot.config.yaml',
    '.sdd/bot/sessions.json',
    '.sdd/bot/versions/',
    'bot/node_modules/',
    'bot/dist/',
    'bot/ecosystem.config.js',
  ]

  let existing = ''
  if (fs.existsSync(gitignorePath)) {
    existing = fs.readFileSync(gitignorePath, 'utf8')
  }

  const toAdd = entries.filter((e) => !existing.includes(e))
  if (toAdd.length > 0) {
    const addition = '\n# sdd-bot (generated by install.js)\n' + toAdd.join('\n') + '\n'
    fs.appendFileSync(gitignorePath, addition, 'utf8')
    console.log('✅  .gitignore updated')
  } else {
    console.log('✅  .gitignore already up to date')
  }
}

// ─── pm2 setup ────────────────────────────────────────────────────────────────

function ensurePm2() {
  const found = runCapture('pm2 --version')
  if (found) {
    console.log(`  pm2 already installed (${found})`)
    return
  }
  console.log('📦  Installing pm2 globally...')
  const r = run('npm install -g pm2')
  if (r.status !== 0) { console.error('❌  pm2 install failed'); process.exit(1) }
  console.log('✅  pm2 installed')
}

function setupPm2Autostart() {
  const platform = os.platform()
  console.log(`\n   Configuring pm2 autostart for platform: ${platform}`)

  // start the app first so pm2 save has something to persist
  const startResult = run('pm2 start ecosystem.config.js', { cwd: __dirname })
  if (startResult.status !== 0) {
    console.warn('⚠️   pm2 start returned non-zero — continuing anyway')
  }

  if (platform === 'win32') {
    // pm2-windows-startup or native Task Scheduler fallback
    const hasWindowsStartup = runCapture('npm list -g pm2-windows-startup')
    if (!hasWindowsStartup || hasWindowsStartup.includes('empty')) {
      console.log('📦  Installing pm2-windows-startup...')
      run('npm install -g pm2-windows-startup')
      run('pm2-startup install')
    } else {
      run('pm2-startup install')
    }
  } else {
    // darwin and linux: pm2 startup generates the appropriate init system command
    const startupOut = runCapture('pm2 startup')
    if (startupOut) {
      // pm2 prints a sudo command — try to run it automatically
      const match = startupOut.match(/sudo\s+.+/)
      if (match) {
        console.log('Running generated startup command (may require sudo):')
        console.log(match[0])
        run(match[0])
      }
    }
  }

  run('pm2 save')
  console.log('✅  pm2 autostart configured and process list saved')
}

// ─── main install flow ────────────────────────────────────────────────────────

async function install() {
  console.log('=== sdd-bot installer ===\n')

  checkNodeVersion()

  npmInstallAndBuild()

  const cfg = await promptConfig()

  console.log('\nValidating connections...')
  const results = await validateConnections(cfg)
  const finalCfg = await retryFailedServices(cfg, results)

  // detect project root (two levels up from bot/)
  const projectRoot = path.resolve(__dirname, '..')

  writeConfigFiles(finalCfg, projectRoot)
  writeEcosystemConfig(projectRoot)
  updateGitignore(projectRoot)
  configureGitRemote(finalCfg, projectRoot)

  ensurePm2()
  setupPm2Autostart()

  console.log('\n🎉  sdd-bot installation complete!')
}

// ─── exports ──────────────────────────────────────────────────────────────────

module.exports = { install, validateConnections, setupPm2Autostart }

if (require.main === module) {
  install().catch((err) => {
    console.error('Installation failed:', err)
    process.exit(1)
  })
}