@delegance/claude-autopilot 1.0.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## [1.2.0] — 2026-04-21
4
+
5
+ ### Added
6
+ - `autopilot doctor` — prerequisite checker: verifies Node 22+, tsx, gh CLI auth, claude CLI, OPENAI_API_KEY, git config, superpowers plugin; shows exact fix command for each failure; exits 1 if any blockers
7
+ - `autopilot setup` now runs `doctor` automatically at the end so users immediately see what still needs attention
8
+ - `autopilot preflight` kept as alias for `doctor`
9
+
10
+ ## [1.1.0] — 2026-04-21
11
+
12
+ ### Added
13
+ - `autopilot setup` — zero-prompt setup: auto-detects project type (Go, Rails, FastAPI, T3, Next.js+Supabase), infers test command, writes config, installs git hook in one command
14
+ - `autopilot setup --force` — overwrite existing config
15
+
3
16
  ## [1.0.2] — 2026-04-21
4
17
 
5
18
  ### Fixed
package/README.md CHANGED
@@ -13,19 +13,15 @@ Requires Node 22+. Also requires `gh` CLI authenticated and `claude` CLI install
13
13
  ## Quick Start
14
14
 
15
15
  ```bash
16
- # Scaffold config
17
- npx autopilot init
16
+ # One command — auto-detects project type, writes config, installs hook
17
+ npx autopilot setup
18
18
 
19
- # Run on changed files
19
+ # Then run your first pipeline
20
20
  npx autopilot run
21
-
22
- # Watch mode (re-runs on every file save)
23
- npx autopilot watch
24
-
25
- # Install pre-push hook
26
- npx autopilot hook install
27
21
  ```
28
22
 
23
+ Requires Node 22+, `gh` CLI authenticated, `claude` CLI (Claude Code).
24
+
29
25
  ## Commands
30
26
 
31
27
  ### `autopilot run`
@@ -77,6 +73,17 @@ npx autopilot autoregress generate --files src/foo.ts,src/bar.ts
77
73
 
78
74
  Requires `OPENAI_API_KEY` for `generate` mode.
79
75
 
76
+ ### `autopilot setup`
77
+
78
+ Zero-prompt setup: auto-detects project type, writes config, installs git hook in one command.
79
+
80
+ ```bash
81
+ npx autopilot setup # Auto-detect project, write config, install hook
82
+ npx autopilot setup --force # Overwrite existing autopilot.config.yaml
83
+ ```
84
+
85
+ Auto-detection supports: Go, Rails, FastAPI, T3, Next.js+Supabase.
86
+
80
87
  ### `autopilot init`
81
88
 
82
89
  Scaffolds `autopilot.config.yaml` from a preset.
@@ -87,9 +94,17 @@ npx autopilot init
87
94
 
88
95
  Available presets: `nextjs-supabase`, `t3`, `python-fastapi`, `rails-postgres`, `go`.
89
96
 
90
- ### `autopilot preflight`
97
+ ### `autopilot doctor`
98
+
99
+ Checks prerequisites and shows exact fix commands for each failure.
100
+
101
+ ```bash
102
+ npx autopilot doctor # Check prerequisites and show exact fix commands
103
+ ```
104
+
105
+ Verifies: Node 22+, tsx, gh CLI auth, claude CLI, OPENAI_API_KEY, git user config, superpowers plugin. Exits 1 if any blockers are found. Also runs automatically at the end of `autopilot setup`.
91
106
 
92
- Checks prerequisites (Node version, `gh` CLI auth, `OPENAI_API_KEY`).
107
+ `autopilot preflight` is kept as an alias for `doctor`.
93
108
 
94
109
  ## GitHub Actions
95
110
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@delegance/claude-autopilot",
3
- "version": "1.0.2",
3
+ "version": "1.2.0",
4
4
  "type": "module",
5
5
  "description": "Claude Code automation pipeline: spec \u2192 plan \u2192 implement \u2192 validate \u2192 PR",
6
6
  "keywords": [
@@ -0,0 +1,72 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+
4
+ export interface DetectionResult {
5
+ preset: string;
6
+ testCommand: string;
7
+ confidence: 'high' | 'low';
8
+ evidence: string;
9
+ }
10
+
11
+ function readJson(filePath: string): Record<string, unknown> | null {
12
+ try {
13
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
14
+ } catch {
15
+ return null;
16
+ }
17
+ }
18
+
19
+ function fileContains(filePath: string, needle: string): boolean {
20
+ try {
21
+ return fs.readFileSync(filePath, 'utf8').includes(needle);
22
+ } catch {
23
+ return false;
24
+ }
25
+ }
26
+
27
+ function nodeTestCommand(cwd: string): string {
28
+ const pkg = readJson(path.join(cwd, 'package.json'));
29
+ const scripts = pkg?.['scripts'] as Record<string, string> | undefined;
30
+ return scripts?.['test'] ?? 'npm test';
31
+ }
32
+
33
+ export function detectProject(cwd: string): DetectionResult {
34
+ if (fs.existsSync(path.join(cwd, 'go.mod'))) {
35
+ return { preset: 'go', testCommand: 'go test ./...', confidence: 'high', evidence: 'found go.mod' };
36
+ }
37
+
38
+ const gemfile = path.join(cwd, 'Gemfile');
39
+ if (fs.existsSync(gemfile) && fileContains(gemfile, 'rails')) {
40
+ return { preset: 'rails-postgres', testCommand: 'bundle exec rails test', confidence: 'high', evidence: "found Gemfile with 'rails'" };
41
+ }
42
+
43
+ const reqTxt = path.join(cwd, 'requirements.txt');
44
+ const pyproject = path.join(cwd, 'pyproject.toml');
45
+ if ((fs.existsSync(reqTxt) && fileContains(reqTxt, 'fastapi')) ||
46
+ (fs.existsSync(pyproject) && fileContains(pyproject, 'fastapi'))) {
47
+ return { preset: 'python-fastapi', testCommand: 'pytest', confidence: 'high', evidence: 'found fastapi in requirements' };
48
+ }
49
+
50
+ const pkgPath = path.join(cwd, 'package.json');
51
+ if (fs.existsSync(pkgPath)) {
52
+ const pkg = readJson(pkgPath);
53
+ const deps = {
54
+ ...(pkg?.['dependencies'] as Record<string, string> ?? {}),
55
+ ...(pkg?.['devDependencies'] as Record<string, string> ?? {}),
56
+ };
57
+ const testCmd = nodeTestCommand(cwd);
58
+
59
+ if ('@trpc/server' in deps) {
60
+ return { preset: 't3', testCommand: testCmd, confidence: 'high', evidence: 'found @trpc/server in package.json' };
61
+ }
62
+ if ('next' in deps && '@supabase/supabase-js' in deps) {
63
+ return { preset: 'nextjs-supabase', testCommand: testCmd, confidence: 'high', evidence: 'found next + @supabase/supabase-js in package.json' };
64
+ }
65
+ if ('next' in deps) {
66
+ return { preset: 'nextjs-supabase', testCommand: testCmd, confidence: 'low', evidence: 'found next in package.json (no supabase detected)' };
67
+ }
68
+ return { preset: 'nextjs-supabase', testCommand: testCmd, confidence: 'low', evidence: 'found package.json (no strong framework signals)' };
69
+ }
70
+
71
+ return { preset: 'nextjs-supabase', testCommand: 'npm test', confidence: 'low', evidence: 'no project signals found — using default preset' };
72
+ }
package/src/cli/index.ts CHANGED
@@ -8,15 +8,17 @@
8
8
  * autopilot run --base main diff against a specific branch
9
9
  * autopilot run --dry-run show what would run, no execution
10
10
  * autopilot watch re-run pipeline on every file save (debounced)
11
- * autopilot preflight check prerequisites
11
+ * autopilot doctor check prerequisites (alias: preflight)
12
12
  */
13
13
  import { runInit } from './init.ts';
14
14
  import { runCommand } from './run.ts';
15
15
  import { runWatch } from './watch.ts';
16
+ import { runSetup } from './setup.ts';
17
+ import { runDoctor } from './preflight.ts';
16
18
 
17
19
  const args = process.argv.slice(2);
18
20
 
19
- const SUBCOMMANDS = ['init', 'run', 'watch', 'hook', 'autoregress', 'preflight', 'help', '--help', '-h'] as const;
21
+ const SUBCOMMANDS = ['init', 'run', 'watch', 'hook', 'autoregress', 'doctor', 'preflight', 'setup', 'help', '--help', '-h'] as const;
20
22
  const VALUE_FLAGS = ['base', 'config', 'files', 'format', 'output', 'debounce'];
21
23
 
22
24
  // Detect first non-flag arg as subcommand, default to 'run'
@@ -46,7 +48,7 @@ Commands:
46
48
  run Run the pipeline on git-changed files (default)
47
49
  watch Watch for file changes and re-run pipeline on each save
48
50
  init Scaffold autopilot.config.yaml from a preset
49
- preflight Check prerequisites
51
+ doctor Check prerequisites and show exact fix commands (alias: preflight)
50
52
  autoregress Run snapshot regression tests (run|diff|update|generate)
51
53
 
52
54
  Options (run):
@@ -74,9 +76,12 @@ switch (subcommand) {
74
76
  await runInit(process.cwd());
75
77
  break;
76
78
 
77
- case 'preflight':
78
- await import('./preflight.ts');
79
+ case 'doctor':
80
+ case 'preflight': {
81
+ const result = await runDoctor();
82
+ process.exit(result.blockers > 0 ? 1 : 0);
79
83
  break;
84
+ }
80
85
 
81
86
  case 'help':
82
87
  case '--help':
@@ -141,6 +146,12 @@ switch (subcommand) {
141
146
  break;
142
147
  }
143
148
 
149
+ case 'setup': {
150
+ const force = args.includes('--force');
151
+ await runSetup({ force });
152
+ break;
153
+ }
154
+
144
155
  default:
145
156
  console.error(`\x1b[31m[autopilot] Unknown subcommand: "${subcommand}"\x1b[0m`);
146
157
  printUsage();
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import * as fs from 'node:fs';
3
3
  import * as path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
4
5
  import { runSafe } from '../core/shell.ts';
5
6
 
6
7
  const PASS = '\x1b[32m✓\x1b[0m';
@@ -30,125 +31,140 @@ function loadEnvFile(filePath: string): Record<string, string> {
30
31
  return vars;
31
32
  }
32
33
 
33
- const checks: Check[] = [];
34
-
35
- // 1. Node version
36
- const nodeVersion = process.version;
37
- const nodeMajor = parseInt(nodeVersion.slice(1).split('.')[0]!, 10);
38
- checks.push({
39
- name: `Node.js ${nodeVersion}`,
40
- result: nodeMajor >= 22 ? 'pass' : 'fail',
41
- message: nodeMajor < 22 ? `Node 22+ required — current: ${nodeVersion}. Install via nvm: nvm install 22` : undefined,
42
- });
43
-
44
- // 2. tsx available
45
- const localTsx = path.join(process.cwd(), 'node_modules', '.bin', 'tsx');
46
- const tsxVersion = fs.existsSync(localTsx)
47
- ? runSafe(localTsx, ['--version'])
48
- : runSafe('tsx', ['--version']);
49
- checks.push({
50
- name: 'tsx available',
51
- result: tsxVersion ? 'pass' : 'fail',
52
- message: !tsxVersion ? 'tsx not found — run: npm install @delegance/claude-autopilot (includes tsx)' : undefined,
53
- });
54
-
55
- // 3. gh CLI authenticated
56
- const ghAuth = runSafe('gh', ['auth', 'status']);
57
- checks.push({
58
- name: 'gh CLI authenticated',
59
- result: ghAuth !== null ? 'pass' : 'fail',
60
- message: ghAuth === null ? 'gh CLI not authenticated — run: gh auth login' : undefined,
61
- });
62
-
63
- // 4. autopilot.config.yaml in cwd
64
- const configYaml = path.join(process.cwd(), 'autopilot.config.yaml');
65
- checks.push({
66
- name: 'autopilot.config.yaml',
67
- result: fs.existsSync(configYaml) ? 'pass' : 'warn',
68
- message: !fs.existsSync(configYaml)
69
- ? 'autopilot.config.yaml not found in current directory — copy from a preset: presets/nextjs-supabase/autopilot.config.yaml'
70
- : undefined,
71
- });
72
-
73
- // 5. Local env file exists
74
- const envFile = ENV_CANDIDATES.find(f => fs.existsSync(f));
75
- checks.push({
76
- name: `Local env file (${envFile ?? 'none found'})`,
77
- result: envFile ? 'pass' : 'warn',
78
- message: !envFile
79
- ? `No env file found. Looked for: ${ENV_CANDIDATES.join(', ')}. Create one with your OPENAI_API_KEY.`
80
- : undefined,
81
- });
82
-
83
- // 6. OPENAI_API_KEY set
84
- const envVars = envFile ? loadEnvFile(envFile) : {};
85
- const hasOpenAI = !!process.env.OPENAI_API_KEY || !!envVars['OPENAI_API_KEY'];
86
- checks.push({
87
- name: 'OPENAI_API_KEY',
88
- result: hasOpenAI ? 'pass' : 'warn',
89
- message: !hasOpenAI
90
- ? `OPENAI_API_KEY not set Codex review steps will be skipped`
91
- : undefined,
92
- });
93
-
94
- // 7. claude CLI available
95
- const claudeVersion = runSafe('claude', ['--version']);
96
- checks.push({
97
- name: 'claude CLI',
98
- result: claudeVersion ? 'pass' : 'fail',
99
- message: !claudeVersion
100
- ? 'claude CLI not found — required for autofix. Install Claude Code: https://claude.ai/claude-code'
101
- : undefined,
102
- });
103
-
104
- // 8. git user config
105
- const gitName = runSafe('git', ['config', 'user.name']);
106
- const gitEmail = runSafe('git', ['config', 'user.email']);
107
- const gitConfigOk = !!(gitName?.trim()) && !!(gitEmail?.trim());
108
- checks.push({
109
- name: 'git user config',
110
- result: gitConfigOk ? 'pass' : 'warn',
111
- message: !gitConfigOk
112
- ? 'git user.name / user.email not set — commits will fail.'
113
- : undefined,
114
- });
115
-
116
- // 9. superpowers plugin
117
- const home = process.env.HOME ?? '';
118
- const superpowersPaths = [
119
- path.join(home, '.claude', 'plugins', 'cache', 'claude-plugins-official', 'superpowers'),
120
- path.join(home, '.claude', 'plugins', 'cache', 'superpowers-marketplace', 'superpowers'),
121
- path.join(home, '.claude', 'plugins', 'superpowers'),
122
- ];
123
- const superpowersOk = superpowersPaths.some(p => fs.existsSync(p));
124
- checks.push({
125
- name: 'superpowers plugin',
126
- result: superpowersOk ? 'pass' : 'warn',
127
- message: !superpowersOk
128
- ? 'superpowers plugin not detected — install: /plugin install superpowers@claude-plugins-official'
129
- : undefined,
130
- });
131
-
132
- // Print results
133
- console.log('\n\x1b[1m[preflight] Autopilot prerequisite check\x1b[0m\n');
134
- let failures = 0;
135
- let warnings = 0;
136
- for (const check of checks) {
137
- const icon = check.result === 'pass' ? PASS : check.result === 'warn' ? WARN : FAIL;
138
- console.log(` ${icon} ${check.name}`);
139
- if (check.message) {
140
- console.log(` \x1b[2m${check.message}\x1b[0m`);
34
+ export interface DoctorResult {
35
+ blockers: number;
36
+ warnings: number;
37
+ }
38
+
39
+ export async function runDoctor(): Promise<DoctorResult> {
40
+ const checks: Check[] = [];
41
+
42
+ // 1. Node version
43
+ const nodeVersion = process.version;
44
+ const nodeMajor = parseInt(nodeVersion.slice(1).split('.')[0]!, 10);
45
+ checks.push({
46
+ name: `Node.js ${nodeVersion}`,
47
+ result: nodeMajor >= 22 ? 'pass' : 'fail',
48
+ message: nodeMajor < 22 ? `Node 22+ required — current: ${nodeVersion}. Install via nvm: nvm install 22` : undefined,
49
+ });
50
+
51
+ // 2. tsx available
52
+ const localTsx = path.join(process.cwd(), 'node_modules', '.bin', 'tsx');
53
+ const tsxVersion = fs.existsSync(localTsx)
54
+ ? runSafe(localTsx, ['--version'])
55
+ : runSafe('tsx', ['--version']);
56
+ checks.push({
57
+ name: 'tsx available',
58
+ result: tsxVersion ? 'pass' : 'fail',
59
+ message: !tsxVersion ? 'tsx not found — run: npm install @delegance/claude-autopilot (includes tsx)' : undefined,
60
+ });
61
+
62
+ // 3. gh CLI authenticated
63
+ const ghAuth = runSafe('gh', ['auth', 'status']);
64
+ checks.push({
65
+ name: 'gh CLI authenticated',
66
+ result: ghAuth !== null ? 'pass' : 'fail',
67
+ message: ghAuth === null ? 'gh CLI not authenticated — run: gh auth login' : undefined,
68
+ });
69
+
70
+ // 4. autopilot.config.yaml in cwd
71
+ const configYaml = path.join(process.cwd(), 'autopilot.config.yaml');
72
+ checks.push({
73
+ name: 'autopilot.config.yaml',
74
+ result: fs.existsSync(configYaml) ? 'pass' : 'warn',
75
+ message: !fs.existsSync(configYaml)
76
+ ? 'autopilot.config.yaml not found in current directory — copy from a preset: presets/nextjs-supabase/autopilot.config.yaml'
77
+ : undefined,
78
+ });
79
+
80
+ // 5. Local env file exists
81
+ const envFile = ENV_CANDIDATES.find(f => fs.existsSync(f));
82
+ checks.push({
83
+ name: `Local env file (${envFile ?? 'none found'})`,
84
+ result: envFile ? 'pass' : 'warn',
85
+ message: !envFile
86
+ ? `No env file found. Looked for: ${ENV_CANDIDATES.join(', ')}. Create one with your OPENAI_API_KEY.`
87
+ : undefined,
88
+ });
89
+
90
+ // 6. OPENAI_API_KEY set
91
+ const envVars = envFile ? loadEnvFile(envFile) : {};
92
+ const hasOpenAI = !!process.env.OPENAI_API_KEY || !!envVars['OPENAI_API_KEY'];
93
+ checks.push({
94
+ name: 'OPENAI_API_KEY',
95
+ result: hasOpenAI ? 'pass' : 'warn',
96
+ message: !hasOpenAI
97
+ ? `OPENAI_API_KEY not set — Codex review steps will be skipped`
98
+ : undefined,
99
+ });
100
+
101
+ // 7. claude CLI available
102
+ const claudeVersion = runSafe('claude', ['--version']);
103
+ checks.push({
104
+ name: 'claude CLI',
105
+ result: claudeVersion ? 'pass' : 'fail',
106
+ message: !claudeVersion
107
+ ? 'claude CLI not found — required for autofix. Install Claude Code: https://claude.ai/claude-code'
108
+ : undefined,
109
+ });
110
+
111
+ // 8. git user config
112
+ const gitName = runSafe('git', ['config', 'user.name']);
113
+ const gitEmail = runSafe('git', ['config', 'user.email']);
114
+ const gitConfigOk = !!(gitName?.trim()) && !!(gitEmail?.trim());
115
+ checks.push({
116
+ name: 'git user config',
117
+ result: gitConfigOk ? 'pass' : 'warn',
118
+ message: !gitConfigOk
119
+ ? 'git user.name / user.email not set — commits will fail.'
120
+ : undefined,
121
+ });
122
+
123
+ // 9. superpowers plugin
124
+ const home = process.env.HOME ?? '';
125
+ const superpowersPaths = [
126
+ path.join(home, '.claude', 'plugins', 'cache', 'claude-plugins-official', 'superpowers'),
127
+ path.join(home, '.claude', 'plugins', 'cache', 'superpowers-marketplace', 'superpowers'),
128
+ path.join(home, '.claude', 'plugins', 'superpowers'),
129
+ ];
130
+ const superpowersOk = superpowersPaths.some(p => fs.existsSync(p));
131
+ checks.push({
132
+ name: 'superpowers plugin',
133
+ result: superpowersOk ? 'pass' : 'warn',
134
+ message: !superpowersOk
135
+ ? 'superpowers plugin not detected — install: /plugin install superpowers@claude-plugins-official'
136
+ : undefined,
137
+ });
138
+
139
+ // Print results
140
+ console.log('\n\x1b[1m[doctor] Autopilot prerequisite check\x1b[0m\n');
141
+ let blockers = 0;
142
+ let warnings = 0;
143
+ for (const check of checks) {
144
+ const icon = check.result === 'pass' ? PASS : check.result === 'warn' ? WARN : FAIL;
145
+ console.log(` ${icon} ${check.name}`);
146
+ if (check.message) {
147
+ console.log(` \x1b[2m${check.message}\x1b[0m`);
148
+ }
149
+ if (check.result === 'fail') blockers++;
150
+ if (check.result === 'warn') warnings++;
141
151
  }
142
- if (check.result === 'fail') failures++;
143
- if (check.result === 'warn') warnings++;
152
+
153
+ console.log('');
154
+ if (blockers > 0) {
155
+ console.log(`\x1b[31m[doctor] ${blockers} blocker(s) — fix before running npx autopilot run\x1b[0m\n`);
156
+ } else if (warnings > 0) {
157
+ console.log(`\x1b[33m[doctor] ${warnings} warning(s) — pipeline will run but some steps may be skipped\x1b[0m\n`);
158
+ } else {
159
+ console.log(`\x1b[32m[doctor] All checks passed — ready to run\x1b[0m\n`);
160
+ }
161
+
162
+ return { blockers, warnings };
144
163
  }
145
164
 
146
- console.log('');
147
- if (failures > 0) {
148
- console.log(`\x1b[31m[preflight] ${failures} check(s) failed — fix before running /autopilot\x1b[0m\n`);
149
- process.exit(1);
150
- } else if (warnings > 0) {
151
- console.log(`\x1b[33m[preflight] ${warnings} warning(s) — pipeline will run but some steps may be degraded\x1b[0m\n`);
152
- } else {
153
- console.log(`\x1b[32m[preflight] All checks passed\x1b[0m\n`);
165
+ // Run when invoked directly
166
+ const isMain = process.argv[1] !== undefined &&
167
+ fileURLToPath(import.meta.url) === path.resolve(process.argv[1]);
168
+ if (isMain) {
169
+ runDoctor().then(r => process.exit(r.blockers > 0 ? 1 : 0));
154
170
  }
@@ -0,0 +1,85 @@
1
+ import * as fs from 'node:fs';
2
+ import * as fsAsync from 'node:fs/promises';
3
+ import * as path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { detectProject } from './detector.ts';
6
+ import { runHook } from './hook.ts';
7
+ import { runDoctor } from './preflight.ts';
8
+
9
+ const PASS = '\x1b[32m✓\x1b[0m';
10
+ const WARN = '\x1b[33m!\x1b[0m';
11
+
12
+ const PRESET_LABELS: Record<string, string> = {
13
+ 'nextjs-supabase': 'Next.js + Supabase',
14
+ 't3': 'T3 Stack (Next.js + tRPC + Prisma)',
15
+ 'rails-postgres': 'Ruby on Rails + PostgreSQL',
16
+ 'python-fastapi': 'Python FastAPI',
17
+ 'go': 'Go + PostgreSQL',
18
+ };
19
+
20
+ export interface SetupOptions {
21
+ cwd?: string;
22
+ force?: boolean;
23
+ skipHook?: boolean;
24
+ }
25
+
26
+ function presetSearchPaths(name: string, cwd: string): string[] {
27
+ const pkgRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
28
+ return [
29
+ path.join(pkgRoot, 'presets', name, 'autopilot.config.yaml'),
30
+ path.join(cwd, 'node_modules', '@delegance', 'claude-autopilot', 'presets', name, 'autopilot.config.yaml'),
31
+ ];
32
+ }
33
+
34
+ function findPresetConfig(name: string, cwd: string): string | null {
35
+ for (const p of presetSearchPaths(name, cwd)) {
36
+ if (fs.existsSync(p)) return p;
37
+ }
38
+ return null;
39
+ }
40
+
41
+ export async function runSetup(options: SetupOptions = {}): Promise<void> {
42
+ const cwd = options.cwd ?? process.cwd();
43
+ const dest = path.join(cwd, 'autopilot.config.yaml');
44
+
45
+ if (fs.existsSync(dest) && !options.force) {
46
+ throw new Error('autopilot.config.yaml already exists — use --force to overwrite');
47
+ }
48
+
49
+ console.log('\n[setup] Detecting project type...');
50
+
51
+ const detection = detectProject(cwd);
52
+ const label = PRESET_LABELS[detection.preset] ?? detection.preset;
53
+
54
+ if (detection.confidence === 'high') {
55
+ console.log(` ${PASS} ${label} (${detection.evidence})`);
56
+ } else {
57
+ console.log(` ${WARN} ${label} — no strong signals found, defaulted to ${detection.preset}`);
58
+ console.log(` \x1b[2mEdit autopilot.config.yaml to switch presets if needed\x1b[0m`);
59
+ }
60
+ console.log(` ${PASS} Test command: ${detection.testCommand}`);
61
+
62
+ const presetConfigPath = findPresetConfig(detection.preset, cwd);
63
+ if (!presetConfigPath) {
64
+ throw new Error(`Preset config not found for: ${detection.preset}. Looked in:\n ${presetSearchPaths(detection.preset, cwd).join('\n ')}`);
65
+ }
66
+
67
+ let presetContent = await fsAsync.readFile(presetConfigPath, 'utf8');
68
+ presetContent = presetContent.trimEnd() + `\ntestCommand: "${detection.testCommand}"\n`;
69
+ await fsAsync.writeFile(dest, presetContent, 'utf8');
70
+ console.log(` ${PASS} Created autopilot.config.yaml`);
71
+
72
+ if (!options.skipHook) {
73
+ const hookCode = await runHook('install', { cwd });
74
+ if (hookCode === 0) {
75
+ console.log(` ${PASS} Installed pre-push git hook`);
76
+ } else {
77
+ console.log(` ${WARN} Hook install failed (not fatal — run: npx autopilot hook install)`);
78
+ }
79
+ }
80
+
81
+ console.log('\n[setup] Checking prerequisites...');
82
+ await runDoctor();
83
+
84
+ console.log('\n[setup] Done. Run: npx autopilot run\n');
85
+ }