-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart.py
More file actions
652 lines (525 loc) · 20.6 KB
/
start.py
File metadata and controls
652 lines (525 loc) · 20.6 KB
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
#!/usr/bin/env python3
"""
Simple CLI launcher for the Autonomous Coding Agent.
Provides an interactive menu to create new projects or continue existing ones.
Supports two paths for new projects:
1. Claude path: Use /create-spec to generate spec interactively
2. Manual path: Edit template files directly, then continue
"""
import os
import subprocess
import sys
from pathlib import Path
from dotenv import load_dotenv
from auth import is_auth_error, print_auth_error_help
# Load environment variables from .env file if present
load_dotenv()
from prompts import (
get_project_prompts_dir,
has_project_prompts,
scaffold_project_prompts,
)
from registry import (
get_project_path,
list_registered_projects,
register_project,
unregister_project,
update_project_path,
)
def check_spec_exists(project_dir: Path) -> bool:
"""
Check if valid spec files exist for a project.
Checks in order:
1. Project prompts directory: {project_dir}/prompts/app_spec.txt
2. Project root (legacy): {project_dir}/app_spec.txt
"""
# Check project prompts directory first
project_prompts = get_project_prompts_dir(project_dir)
spec_file = project_prompts / "app_spec.txt"
if spec_file.exists():
try:
content = spec_file.read_text(encoding="utf-8")
return "<project_specification>" in content
except (OSError, PermissionError):
return False
# Check legacy location in project root
legacy_spec = project_dir / "app_spec.txt"
if legacy_spec.exists():
try:
content = legacy_spec.read_text(encoding="utf-8")
return "<project_specification>" in content
except (OSError, PermissionError):
return False
return False
def get_existing_projects() -> list[tuple[str, Path]]:
"""Get list of existing projects from registry.
Returns:
List of (name, path) tuples for registered projects that still exist.
"""
registry = list_registered_projects()
projects = []
for name, info in registry.items():
path = Path(info["path"])
if path.exists():
projects.append((name, path))
return sorted(projects, key=lambda x: x[0])
def display_menu(projects: list[tuple[str, Path]]) -> None:
"""Display the main menu."""
print("\n" + "=" * 50)
print(" Autonomous Coding Agent Launcher")
print("=" * 50)
print("\n[1] Create new project")
if projects:
print("[2] Continue existing project")
print("[3] Edit project settings")
print("[q] Quit")
print()
def display_projects(projects: list[tuple[str, Path]]) -> None:
"""Display list of existing projects with file counts."""
from progress import count_passing_tests
print("\n" + "-" * 40)
print(" Existing Projects")
print("-" * 40)
for i, (name, path) in enumerate(projects, 1):
# Get file info
spec_exists = check_spec_exists(path)
db_exists = (path / "features.db").exists()
# Count features if db exists
feature_count = 0
passing_count = 0
if db_exists:
try:
passing, _, total = count_passing_tests(path)
feature_count = total
passing_count = passing
except:
pass
# Display with icons
spec_icon = "✓" if spec_exists else "○"
db_icon = "✓" if db_exists else "○"
print(f" [{i}] {name}")
print(f" Path: {path}")
if db_exists and feature_count > 0:
print(f" {spec_icon} Spec {db_icon} Database ({passing_count}/{feature_count} passing)")
else:
print(f" {spec_icon} Spec {db_icon} Database")
print()
print(" [b] Back to main menu")
print()
def get_project_choice(projects: list[tuple[str, Path]]) -> tuple[str, Path] | None:
"""Get user's project selection.
Returns:
Tuple of (name, path) for the selected project, or None if cancelled.
"""
while True:
choice = input("Select project number: ").strip().lower()
if choice == 'b':
return None
try:
idx = int(choice) - 1
if 0 <= idx < len(projects):
return projects[idx]
print(f"Please enter a number between 1 and {len(projects)}")
except ValueError:
print("Invalid input. Enter a number or 'b' to go back.")
def get_new_project_info() -> tuple[str, Path] | None:
"""Get name and path for new project.
Returns:
Tuple of (name, path) for the new project, or None if cancelled.
"""
print("\n" + "-" * 40)
print(" Create New Project")
print("-" * 40)
print("\nEnter project name (e.g., my-awesome-app)")
print("Leave empty to cancel.\n")
name = input("Project name: ").strip()
if not name:
return None
# Basic validation - OS-aware invalid characters
# Windows has more restrictions than Unix
if sys.platform == "win32":
invalid_chars = '<>:"/\\|?*'
else:
# Unix only restricts / and null
invalid_chars = '/'
for char in invalid_chars:
if char in name:
print(f"Invalid character '{char}' in project name")
return None
# Check if name already registered
existing = get_project_path(name)
if existing:
print(f"Project '{name}' already exists at {existing}")
return None
# Get project path
print("\nEnter the full path for the project directory")
print("(e.g., C:/Projects/my-app or /home/user/projects/my-app)")
print("Leave empty to cancel.\n")
path_str = input("Project path: ").strip()
if not path_str:
return None
project_path = Path(path_str).resolve()
return name, project_path
def ensure_project_scaffolded(project_name: str, project_dir: Path) -> Path:
"""
Ensure project directory exists with prompt templates and is registered.
Creates the project directory, copies template files, and registers in registry.
Args:
project_name: Name of the project
project_dir: Absolute path to the project directory
Returns:
The project directory path
"""
# Create project directory if it doesn't exist
project_dir.mkdir(parents=True, exist_ok=True)
# Scaffold prompts (copies templates if they don't exist)
print(f"\nSetting up project: {project_name}")
print(f"Location: {project_dir}")
scaffold_project_prompts(project_dir)
# Register in registry
register_project(project_name, project_dir)
return project_dir
def run_spec_creation(project_dir: Path) -> bool:
"""
Run Claude Code with /create-spec command to create project specification.
The project path is passed as an argument so create-spec knows where to write files.
Captures stderr to detect authentication errors and provide helpful guidance.
"""
print("\n" + "=" * 50)
print(" Project Specification Setup")
print("=" * 50)
print(f"\nProject directory: {project_dir}")
print(f"Prompts will be saved to: {get_project_prompts_dir(project_dir)}")
print("\nLaunching Claude Code for interactive spec creation...")
print("Answer the questions to define your project.")
print("When done, Claude will generate the spec files.")
print("Exit Claude Code (Ctrl+C or /exit) when finished.\n")
try:
# Launch CLI with /create-spec command
# Project path included in command string so it populates $ARGUMENTS
# Capture stderr to detect auth errors while letting stdout flow to terminal
result = subprocess.run(
["claude", f"/create-spec {project_dir}"],
check=False, # Don't raise on non-zero exit
cwd=str(Path(__file__).parent), # Run from project root
stderr=subprocess.PIPE,
text=True
)
# Check for authentication errors in stderr
stderr_output = result.stderr or ""
if result.returncode != 0 and is_auth_error(stderr_output):
print_auth_error_help()
return False
# If there was stderr output but not an auth error, show it
if stderr_output.strip() and result.returncode != 0:
print(f"\nClaude CLI error: {stderr_output.strip()}")
# Check if spec was created in project prompts directory
if check_spec_exists(project_dir):
print("\n" + "-" * 50)
print("Spec files created successfully!")
return True
else:
print("\n" + "-" * 50)
print("Spec creation incomplete.")
print(f"Please ensure app_spec.txt exists in: {get_project_prompts_dir(project_dir)}")
# If failed with non-zero exit and no spec, might be auth issue
if result.returncode != 0:
print("\nIf you're having authentication issues, try running: claude login")
return False
except FileNotFoundError:
print("\nError: 'claude' command not found.")
print("Make sure Claude Code CLI is installed:")
print(" npm install -g @anthropic-ai/claude-code")
return False
except KeyboardInterrupt:
print("\n\nSpec creation cancelled.")
return False
def run_manual_spec_flow(project_dir: Path) -> bool:
"""
Guide user through manual spec editing flow.
Shows the paths to edit and waits for user to press Enter when ready.
"""
prompts_dir = get_project_prompts_dir(project_dir)
print("\n" + "-" * 50)
print(" Manual Specification Setup")
print("-" * 50)
print("\nTemplate files have been created. Edit these files in your editor:")
print("\n Required:")
print(f" {prompts_dir / 'app_spec.txt'}")
print("\n Optional (customize agent behavior):")
print(f" {prompts_dir / 'initializer_prompt.md'}")
print(f" {prompts_dir / 'coding_prompt.md'}")
print("\n" + "-" * 50)
print("\nThe app_spec.txt file contains a template with placeholders.")
print("Replace the placeholders with your actual project specification.")
print("\nWhen you're done editing, press Enter to continue...")
try:
input()
except KeyboardInterrupt:
print("\n\nCancelled.")
return False
# Validate that spec was edited
if check_spec_exists(project_dir):
print("\nSpec file validated successfully!")
return True
else:
print("\nWarning: The app_spec.txt file still contains the template placeholder.")
print("The agent may not work correctly without a proper specification.")
confirm = input("Continue anyway? [y/N]: ").strip().lower()
return confirm == 'y'
def ask_spec_creation_choice() -> str | None:
"""Ask user whether to create spec with Claude, manually, or import PRD."""
print("\n" + "-" * 40)
print(" Specification Setup")
print("-" * 40)
print("\nHow would you like to define your project?")
print("\n[1] Create spec with Claude (recommended)")
print(" Interactive conversation to define your project")
print("\n[2] Edit templates manually")
print(" Edit the template files directly in your editor")
print("\n[3] Import existing PRD")
print(" Load a PRD from a file (Markdown, TXT, or XML)")
print("\n[b] Back to main menu")
print()
while True:
choice = input("Select [1/2/3/b]: ").strip().lower()
if choice in ['1', '2', '3', 'b']:
return choice
print("Invalid choice. Please enter 1, 2, 3, or b.")
def run_prd_import_flow(project_dir: Path) -> bool:
"""
Import PRD from file and convert to app_spec.txt.
Returns:
True if successful, False otherwise
"""
print("\n" + "=" * 50)
print(" Import Existing PRD")
print("=" * 50)
# Get PRD file path
prd_path = input("\nEnter path to PRD file (Markdown, TXT, or XML): ").strip()
if not prd_path:
print("Cancelled.")
return False
prd_file = Path(prd_path)
if not prd_file.exists():
print(f"Error: File not found: {prd_file}")
return False
# Read PRD content
try:
content = prd_file.read_text(encoding='utf-8')
except Exception as e:
print(f"Error reading file: {e}")
return False
spec_file = get_project_prompts_dir(project_dir) / "app_spec.txt"
# Detect format
if content.strip().startswith('<project_specification>'):
# Already in XML format
print("\nDetected XML format - copying directly...")
spec_file.write_text(content, encoding='utf-8')
print(f"✓ Imported to {spec_file}")
return True
else:
# Markdown or plain text - needs conversion
print("\nDetected Markdown/Text format")
print("Converting to XML specification format...")
print("(Wrapping in <project_specification> tags)\n")
# Wrap the content in XML tags
wrapped_content = f"""<project_specification>
<project_name>Imported Project</project_name>
<description>
{content}
</description>
<features>
<!-- Features will be extracted by the initializer agent from the description above -->
</features>
</project_specification>
"""
spec_file.write_text(wrapped_content, encoding='utf-8')
print(f"✓ Imported and wrapped PRD in {spec_file}")
print("\nNote: The initializer agent will extract features from your PRD.")
return True
def create_new_project_flow() -> tuple[str, Path] | None:
"""
Complete flow for creating a new project.
1. Get project name and path
2. Create project directory and scaffold prompts
3. Ask: Claude, Manual, or Import PRD?
4. If Claude: Run /create-spec with project path
5. If Manual: Show paths, wait for Enter
6. If Import: Import PRD file
7. Return (name, path) tuple if successful
"""
project_info = get_new_project_info()
if not project_info:
return None
project_name, project_path = project_info
# Create project directory and scaffold prompts FIRST
project_dir = ensure_project_scaffolded(project_name, project_path)
# Ask user how they want to handle spec creation
choice = ask_spec_creation_choice()
if choice == 'b':
return None
elif choice == '1':
# Create spec with Claude
success = run_spec_creation(project_dir)
if not success:
print("\nYou can try again later or edit the templates manually.")
retry = input("Start agent anyway? [y/N]: ").strip().lower()
if retry != 'y':
return None
elif choice == '2':
# Manual mode - guide user through editing
success = run_manual_spec_flow(project_dir)
if not success:
return None
elif choice == '3':
# Import PRD
success = run_prd_import_flow(project_dir)
if not success:
print("\nYou can try again later or use option [1] or [2].")
retry = input("Start agent anyway? [y/N]: ").strip().lower()
if retry != 'y':
return None
return project_name, project_dir
def run_agent(project_name: str, project_dir: Path) -> None:
"""Run the autonomous agent with the given project.
Captures stderr to detect authentication errors and provide helpful guidance.
Args:
project_name: Name of the project
project_dir: Absolute path to the project directory
"""
# Final validation before running
if not has_project_prompts(project_dir):
print(f"\nWarning: No valid spec found for project '{project_name}'")
print("The agent may not work correctly.")
confirm = input("Continue anyway? [y/N]: ").strip().lower()
if confirm != 'y':
return
print(f"\nStarting agent for project: {project_name}")
print(f"Location: {project_dir}")
print("-" * 50)
# Build the command - pass absolute path
cmd = [sys.executable, "autonomous_agent_demo.py", "--project-dir", str(project_dir.resolve())]
# Run the agent with stderr capture to detect auth errors
# stdout goes directly to terminal for real-time output
try:
result = subprocess.run(
cmd,
check=False,
stderr=subprocess.PIPE,
text=True
)
# Check for authentication errors
stderr_output = result.stderr or ""
if result.returncode != 0:
if is_auth_error(stderr_output):
print_auth_error_help()
elif stderr_output.strip():
# Show any other errors
print(f"\nAgent error:\n{stderr_output.strip()}")
# Still hint about auth if exit was unexpected
if "error" in stderr_output.lower() or "exception" in stderr_output.lower():
print("\nIf this is an authentication issue, try running: claude login")
except KeyboardInterrupt:
print("\n\nAgent interrupted. Run again to resume.")
def display_edit_menu(projects: list[tuple[str, Path]]) -> None:
"""Display projects with edit options."""
print("\n" + "-" * 40)
print(" Edit Project Settings")
print("-" * 40)
for i, (name, path) in enumerate(projects, 1):
print(f" [{i}] {name} ({path})")
print("\n [b] Back to main menu")
print()
def edit_project_settings(project_name: str, project_path: Path) -> None:
"""Edit project name or path."""
while True:
print(f"\n" + "=" * 50)
print(f" Editing: {project_name}")
print("=" * 50)
print(f"Path: {project_path}")
print("\n[1] Rename project")
print("[2] Change project folder")
print("[3] Delete project")
print("[b] Back")
print()
choice = input("Select option: ").strip().lower()
if choice == '1':
new_name = input("\nNew project name: ").strip()
if not new_name:
print("Cancelled.")
continue
# Validate and update registry
try:
unregister_project(project_name)
register_project(new_name, project_path)
print(f"\n✓ Renamed to '{new_name}'")
break
except Exception as e:
# Re-register with old name if something went wrong
try:
register_project(project_name, project_path)
except:
pass
print(f"\nError: {e}")
elif choice == '2':
new_path = input("\nNew project path: ").strip()
if not new_path:
print("Cancelled.")
continue
# Validate and update
try:
new_path_obj = Path(new_path).resolve()
if not new_path_obj.exists():
print(f"Error: Path does not exist: {new_path_obj}")
continue
update_project_path(project_name, new_path_obj)
print(f"\n✓ Updated path to '{new_path_obj}'")
break
except Exception as e:
print(f"\nError: {e}")
elif choice == '3':
confirm = input(f"\nDelete '{project_name}' from registry? (yes/no): ").strip().lower()
if confirm == 'yes':
unregister_project(project_name)
print(f"\n✓ Deleted '{project_name}' from registry")
print("(Project files were not deleted)")
break
else:
print("Cancelled.")
elif choice == 'b':
break
else:
print("Invalid option. Please try again.")
def main() -> None:
"""Main entry point."""
# Ensure we're in the right directory
script_dir = Path(__file__).parent.absolute()
os.chdir(script_dir)
while True:
projects = get_existing_projects()
display_menu(projects)
choice = input("Select option: ").strip().lower()
if choice == 'q':
print("\nGoodbye!")
break
elif choice == '1':
result = create_new_project_flow()
if result:
project_name, project_dir = result
run_agent(project_name, project_dir)
elif choice == '2' and projects:
display_projects(projects)
selected = get_project_choice(projects)
if selected:
project_name, project_dir = selected
run_agent(project_name, project_dir)
elif choice == '3' and projects:
display_edit_menu(projects)
selected = get_project_choice(projects)
if selected:
edit_project_settings(*selected)
else:
print("Invalid option. Please try again.")
if __name__ == "__main__":
main()