-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathrun
More file actions
executable file
·3246 lines (2749 loc) · 129 KB
/
run
File metadata and controls
executable file
·3246 lines (2749 loc) · 129 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
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
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
run - Cross-platform CLI tool for Deft framework
A layered framework for AI-assisted development
Works on: macOS, Linux, Windows, FreeBSD
Optional: rich (for enhanced output and better UX)
"""
import sys
import os
import json
import shutil
import subprocess
from pathlib import Path
from datetime import datetime
from typing import List, Optional
VERSION = "0.4.3"
# Try to import rich for enhanced experience
try:
from rich.console import Console
from rich.prompt import Prompt, Confirm
from rich.panel import Panel
from rich.markdown import Markdown
from rich.text import Text
HAS_RICH = True
console = Console()
except ImportError:
HAS_RICH = False
console = None
# Fall back to readline on Unix for arrow key support
try:
import readline # Enable history and arrow keys on Unix
except ImportError:
pass # Windows: basic input() still works
# Try to import prompt_toolkit
try:
import prompt_toolkit
HAS_PROMPT_TOOLKIT = True
except ImportError:
HAS_PROMPT_TOOLKIT = False
# Try to import textual for TUI mode
try:
from textual.app import App, ComposeResult
from textual.screen import Screen
from textual.widgets import Header, Footer, Button, Label, Input, Select, OptionList, Static, MarkdownViewer, Checkbox
from textual.widgets._option_list import Option
from textual.containers import Container, Horizontal, Vertical, ScrollableContainer
HAS_TEXTUAL = True
except ImportError:
HAS_TEXTUAL = False
# Output helpers
def print_header(text: str):
"""Print main command header"""
if HAS_RICH:
console.print(Panel(f"[bold cyan]{text}[/bold cyan]", border_style="cyan"))
else:
print(f"\n{'=' * 60}")
print(f" {text}")
print('=' * 60)
def print_section(text: str):
"""Print section header within a command"""
if HAS_RICH:
console.print(Markdown(f"## {text}"))
else:
print(f"\n{'-' * 60}")
print(f" {text}")
print('-' * 60)
def print_info(msg: str):
"""Print info message"""
if HAS_RICH:
console.print(f"[blue]ℹ[/blue] {msg}")
else:
print(f"ℹ {msg}")
def print_success(msg: str):
"""Print success message"""
if HAS_RICH:
console.print(f"[green]✓[/green] {msg}")
else:
print(f"✓ {msg}")
def print_warn(msg: str):
"""Print warning message"""
if HAS_RICH:
console.print(f"[yellow]⚠[/yellow] {msg}")
else:
print(f"⚠ {msg}")
def print_error(msg: str):
"""Print error message"""
if HAS_RICH:
console.print(f"[red]✗[/red] {msg}")
else:
print(f"✗ {msg}")
# Legacy aliases for backward compatibility
info = print_info
success = print_success
warn = print_warn
error = print_error
def get_script_dir() -> Path:
"""Get the directory where this script is located"""
return Path(__file__).parent.absolute()
def resolve_path(path_str: str) -> Path:
"""Resolve a user-supplied path string to an absolute Path.
Expands ~ and resolves relative paths against cwd.
"""
return Path(path_str).expanduser().resolve()
def get_default_paths() -> dict:
"""Return default output paths for all generated files.
Environment variables override built-in defaults:
DEFT_USER_PATH default: ~/.config/deft/USER.md
DEFT_PROJECT_PATH default: ./PROJECT.md
DEFT_PRD_PATH default: ./PRD.md
DEFT_SPECIFICATION_PATH default: ./SPECIFICATION.md
DEFT_INTERVIEW_PATH default: ./INTERVIEW.md (Light sizing path only; not in returned dict)
Returns:
dict with keys 'user', 'project', 'prd', 'specification'
"""
return {
'user': os.environ.get('DEFT_USER_PATH', '~/.config/deft/USER.md'),
'project': os.environ.get('DEFT_PROJECT_PATH', './PROJECT.md'),
'prd': os.environ.get('DEFT_PRD_PATH', './PRD.md'),
'specification': os.environ.get('DEFT_SPECIFICATION_PATH', './SPECIFICATION.md'),
}
# ── Resume / atomic-write helpers (issue #8) ─────────────────────────
def _progress_path(output_file: Path) -> Path:
"""Return the progress-file path for a given output file.
Convention: .{filename}.progress in the same directory.
"""
return output_file.parent / f".{output_file.name}.progress"
def _save_progress(prog_file: Path, data: dict):
"""Persist questionnaire progress to a JSON file (best-effort)."""
try:
prog_file.parent.mkdir(parents=True, exist_ok=True)
tmp = prog_file.parent / f".{prog_file.name}.tmp"
tmp.write_text(json.dumps(data, indent=2), encoding='utf-8')
os.replace(str(tmp), str(prog_file))
except OSError:
pass
def _load_progress(prog_file: Path) -> dict:
"""Load saved questionnaire progress. Returns {} on missing/corrupt file."""
if not prog_file.exists():
return {}
try:
return json.loads(prog_file.read_text(encoding='utf-8'))
except (json.JSONDecodeError, OSError):
return {}
def _clear_progress(prog_file: Path):
"""Delete a progress file if it exists."""
try:
if prog_file.exists():
prog_file.unlink()
except OSError:
pass
def _atomic_write(target: Path, content: str):
"""Write *content* to *target* via temp + rename for crash safety."""
target.parent.mkdir(parents=True, exist_ok=True)
tmp = target.parent / f".{target.name}.tmp"
tmp.write_text(content, encoding='utf-8')
os.replace(str(tmp), str(target))
def _resume_or_ask(progress: dict, prog_file: Path, key: str,
label: str, ask_fn, *args, **kwargs):
"""Return a saved answer from *progress*, or call *ask_fn* and persist it."""
if key in progress:
info(f" [resumed] {label}: {progress[key]}")
return progress[key]
val = ask_fn(*args, **kwargs)
progress[key] = val
_save_progress(prog_file, progress)
return val
# Legacy path helpers for backward compatibility
def _legacy_user_path() -> Path:
"""Old location for user.md (inside deft framework dir)."""
return get_script_dir() / "core" / "user.md"
def _legacy_project_path() -> Path:
"""Old location for project.md (inside deft framework dir)."""
return Path("./deft/core/project.md")
# Non-language support files to exclude from language selection
_NON_LANGUAGE_FILES = {'commands', 'markdown', 'mermaid'}
# Display name overrides for language file stems
_LANGUAGE_DISPLAY_NAMES = {
'cpp': 'C++',
'c#': 'C#',
'c': 'C',
'r': 'R',
'sql': 'SQL',
'vhdl': 'VHDL',
'javascript': 'JavaScript',
'typescript': 'TypeScript',
'visual-basic': 'Visual Basic',
}
def get_available_languages() -> List[tuple]:
"""Scan languages/ directory and return available programming languages.
Returns:
Sorted list of (stem, display_name) tuples.
Excludes non-language support files (commands, markdown, mermaid).
"""
lang_dir = get_script_dir() / "languages"
if not lang_dir.is_dir():
return []
languages = []
for f in lang_dir.glob("*.md"):
stem = f.stem
if stem.lower() in _NON_LANGUAGE_FILES:
continue
display = _LANGUAGE_DISPLAY_NAMES.get(
stem, _LANGUAGE_DISPLAY_NAMES.get(
stem.lower(), stem.replace('-', ' ').title()))
languages.append((stem, display))
return sorted(languages, key=lambda x: x[1].lower())
def _lang_widget_id(stem: str) -> str:
"""Create a valid Textual widget ID from a language file stem."""
return "lang_" + stem.replace('#', 'sharp').replace('+', 'plus')
# Non-strategy support files to exclude from strategy selection
# Includes aliases (brownfield, default) which are internal and should not appear in the picker
_NON_STRATEGY_FILES = {'readme', 'brownfield', 'default'}
# Display name overrides for strategy file stems
_STRATEGY_DISPLAY_NAMES = {
'speckit': 'SpecKit',
}
# One-line descriptions shown in strategy picker
_STRATEGY_DESCRIPTIONS = {
'interview': 'Structured interview with sizing gate — Light (embedded spec) or Full (PRD → spec)',
'yolo': 'Auto-pilot interview — Johnbot picks all recommended options',
'map': 'Analyze existing codebase conventions before adding features',
'discuss': 'Front-load decisions and alignment before planning',
'research': 'Investigate the domain before planning',
'speckit': 'Five-phase spec-driven workflow for large/complex projects',
# 'default' and 'brownfield' are aliases excluded via _NON_STRATEGY_FILES — no entries needed here
}
def get_available_strategies() -> List[tuple]:
"""Scan strategies/ directory and return available strategies.
Returns:
Sorted list of (stem, display_name) tuples.
Excludes non-strategy support files (README).
"""
strat_dir = get_script_dir() / "strategies"
if not strat_dir.is_dir():
return []
strategies = []
for f in strat_dir.glob("*.md"):
stem = f.stem
if stem.lower() in _NON_STRATEGY_FILES:
continue
display = _STRATEGY_DISPLAY_NAMES.get(
stem, _STRATEGY_DISPLAY_NAMES.get(
stem.lower(), stem.replace('-', ' ').title()))
strategies.append((stem, display))
return sorted(strategies, key=lambda x: x[1].lower())
def usage():
"""Print usage information"""
hint = ""
if not HAS_RICH:
# Get the Python executable path for accurate install command
python_exe = sys.executable
stdlib_path = Path(sys.base_prefix) / "lib" / f"python{sys.version_info.major}.{sys.version_info.minor}"
is_externally_managed = (stdlib_path / "EXTERNALLY-MANAGED").exists()
install_cmd = f"{python_exe} -m pip install"
if is_externally_managed:
install_cmd += " --break-system-packages"
install_cmd += " rich"
hint = f"\n💡 Tip: Install rich for enhanced output and better UX:\n {install_cmd}\n"
tui_hint = ""
if HAS_TEXTUAL:
tui_hint = " run # Launch TUI wizard (no args)\n run tui # Launch TUI wizard\n run wizard # Launch TUI wizard\n "
if HAS_RICH:
print_header(f"Deft CLI v{VERSION}")
tui_section = "[bold]TUI Mode:[/bold]\n run / run tui / run wizard Launch interactive wizard\n\n" if HAS_TEXTUAL else ""
console.print(f"""
{tui_section}[bold]Usage:[/bold] run <command> [options]
run -h, --help, -help # Show this help
python run <command> [options] # If not executable
python3 run <command> [options] # If not executable
[bold cyan]Commands:[/bold cyan]
[green]bootstrap[/green] Set up your user preferences (user.md)
[green]project[/green] Create/update project configuration (project.md)
[green]spec[/green] Generate project specification via interview (--force to overwrite)
[green]install[/green] Install deft framework in a project directory
[green]reset[/green] Reset configuration files to default state
[green]validate[/green] Validate deft configuration files
[green]update[/green] Update deft framework to latest version
[green]doctor[/green] Check system dependencies and configuration
[green]help[/green] Show this help message
[bold cyan]Examples:[/bold cyan]
run # Launch TUI wizard (if textual installed)
run bootstrap # First-time setup
run project # Configure current project
run spec # Generate SPECIFICATION.md
run install ~/my-project # Install deft in a project
run reset # Reset config files (interactive)
run reset --all # Reset all config files (no prompts)
run validate # Check configuration is valid
For more information: [link]https://github.com/deftai/directive[/link]
""")
else:
tui_section = f"TUI Mode:\n{tui_hint}\n" if HAS_TEXTUAL else ""
print(f"""Deft CLI v{VERSION}{hint}
{tui_section}Usage: run <command> [options]
run -h, --help, -help # Show this help
python run <command> [options] # If not executable
python3 run <command> [options] # If not executable
Commands:
bootstrap Set up your user preferences (user.md)
project Create/update project configuration (project.md)
spec Generate project specification via interview (--force to overwrite)
install Install deft framework in a project directory
reset Reset configuration files to default state
validate Validate deft configuration files
update Update deft framework to latest version
doctor Check system dependencies and configuration
help Show this help message
Examples:
run # Launch TUI wizard (if textual installed)
run bootstrap # First-time setup
run project # Configure current project
run spec # Generate SPECIFICATION.md
run install ~/my-project # Install deft in a project
run reset # Reset config files (interactive)
run reset --all # Reset all config files (no prompts)
run validate # Check configuration is valid
For more information: https://github.com/deftai/directive
""")
def ask_input(prompt_text: str, default: str = "") -> str:
"""Read user input with optional default
Args:
prompt_text: The prompt to display
default: Default value if user presses Enter
Returns:
User input or default value
"""
try:
# Priority: prompt_toolkit (best editing) > rich > basic input
if HAS_PROMPT_TOOLKIT:
from prompt_toolkit import prompt as pt_prompt
from prompt_toolkit.formatted_text import HTML
# Add colored prefix if rich is also available
if HAS_RICH:
display_prompt = HTML(f'<ansibrightcyan>?</ansibrightcyan> {prompt_text}: ')
else:
display_prompt = prompt_text + ": "
value = pt_prompt(display_prompt, default=default)
return value if value else default
elif HAS_RICH:
# Add colored question mark prefix
formatted_prompt = f"[cyan]?[/cyan] {prompt_text}"
value = Prompt.ask(formatted_prompt, default=default if default else None)
return value if value else default
else:
# Fall back to basic input() with readline support (if available on Unix)
if default:
value = input(f"{prompt_text} [{default}]: ")
else:
value = input(f"{prompt_text}: ")
return value if value else default
except EOFError:
return default
def ask_choice(prompt_text: str, choices: List[str], default: str = None) -> str:
"""Read user choice from list
Args:
prompt_text: The prompt to display
choices: List of valid choices
default: Default choice
Returns:
User's choice
"""
try:
if HAS_RICH:
# Add colored question mark prefix
formatted_prompt = f"[cyan]?[/cyan] {prompt_text}"
return Prompt.ask(formatted_prompt, choices=choices, default=default)
else:
# Fallback: show numbered list
print(f"\n{prompt_text}")
for i, choice in enumerate(choices, 1):
print(f" {i}. {choice}")
while True:
ans = input("Enter number: ")
try:
idx = int(ans) - 1
if 0 <= idx < len(choices):
return choices[idx]
except ValueError:
pass
print("Invalid choice, try again.")
except EOFError:
return default if default else choices[0]
def ask_confirm(prompt_text: str, default: bool = False) -> bool:
"""Read yes/no confirmation
Args:
prompt_text: The prompt to display
default: Default value
Returns:
True if user confirms, False otherwise
"""
try:
# Priority: prompt_toolkit > rich > basic input
if HAS_PROMPT_TOOLKIT:
from prompt_toolkit import prompt as pt_prompt
from prompt_toolkit.formatted_text import HTML
# Add colored prefix if rich is also available
suffix = " (Y/n): " if default else " (y/N): "
if HAS_RICH:
display_prompt = HTML(f'<ansibrightcyan>?</ansibrightcyan> {prompt_text}{suffix}')
else:
display_prompt = prompt_text + suffix
response = pt_prompt(display_prompt, default="")
if not response:
return default
return response.strip().lower() in ('y', 'yes')
elif HAS_RICH:
# Add colored question mark prefix
formatted_prompt = f"[cyan]?[/cyan] {prompt_text}"
return Confirm.ask(formatted_prompt, default=default)
else:
suffix = " (Y/n) " if default else " (y/N) "
response = input(f"{prompt_text}{suffix}")
if not response:
return default
return response.strip().lower() in ('y', 'yes')
except EOFError:
return default
# Legacy aliases
read_input = ask_input
read_yn = ask_confirm
def cmd_bootstrap(args: List[str]):
"""Bootstrap command - set up user.md"""
print_header(f"Deft CLI v{VERSION} - Bootstrap")
print()
info("This command creates user.md, which defines YOUR personal preferences:")
info(" • Your name (how the AI should address you)")
info(" • Primary programming languages")
info(" • Default test coverage threshold")
info(" • Development strategy")
info(" • Custom rules and experimental guidelines")
print()
info("These preferences apply across all your projects and only need to be set once.")
info("You can update them anytime by editing user.md or re-running bootstrap.")
print()
defaults = get_default_paths()
# Resume support (issue #8)
prog_file = _progress_path(resolve_path(defaults['user']))
progress = {}
if prog_file.exists():
saved = _load_progress(prog_file)
if saved:
print_section("Previous Session Found")
for k, v in saved.items():
if not k.startswith('_'):
info(f" {k}: {v}")
print()
if read_yn("Resume where you left off?", default=True):
progress = saved
else:
_clear_progress(prog_file)
if 'output_path' not in progress:
print_section("Output Location")
user_path_str = _resume_or_ask(progress, prog_file, 'output_path', 'Output',
read_input, "Where to write USER.md", defaults['user'])
user_file = resolve_path(user_path_str)
# Check if file exists (skip when resuming — user already committed)
if not progress.get('user_name'):
if user_file.exists() and "--force" not in args:
info(f"USER.md already exists at {user_file}")
if not read_yn("Overwrite with new preferences?"):
success("Keeping existing USER.md as-is.")
print()
# Still offer next steps even when keeping existing file
print_section("Next Steps")
if read_yn("Would you like to run 'run project' now?", default=True):
print()
return cmd_project([])
else:
print()
info("You can run 'run project' later to configure your project")
return 0
if 'user_name' not in progress:
print()
print_section("User Preferences Setup")
# Gather user information
user_name = _resume_or_ask(progress, prog_file, 'user_name', 'Name',
read_input, "Your name (how AI should address you)")
if 'coverage' not in progress:
while True:
coverage = read_input("Default coverage threshold (default: 85%)", "85")
if not coverage.strip():
coverage = "85"
break
try:
val = int(coverage.strip())
if 1 <= val <= 100:
break
except ValueError:
pass
print_error("Please enter a number between 1 and 100.")
progress['coverage'] = coverage
_save_progress(prog_file, progress)
else:
coverage = progress['coverage']
info(f" [resumed] Coverage: {coverage}")
available_langs = get_available_languages()
other_num = len(available_langs) + 1
valid_lang_nums = set(str(i) for i in range(1, other_num + 1))
if 'lang_selection' not in progress:
print()
print_section("Programming Languages")
info("Select your primary programming languages (comma-separated):")
for i, (stem, display) in enumerate(available_langs, 1):
print(f" {i}. {display}")
print(f" {other_num}. Other")
while True:
lang_selection = read_input("Selection (e.g., 1,3 or Enter to skip)")
if not lang_selection.strip():
break # Skip
nums = [s.strip() for s in lang_selection.split(',')]
if len(nums) != len(set(nums)):
print_error("Duplicate selections are not allowed.")
continue
if all(n in valid_lang_nums for n in nums):
break
print_error(f"Please enter numbers between 1 and {other_num} (comma-separated).")
progress['lang_selection'] = lang_selection
_save_progress(prog_file, progress)
else:
lang_selection = progress['lang_selection']
info(f" [resumed] Languages: {lang_selection or '(skipped)'}")
lang_nums = [s.strip() for s in lang_selection.split(',')]
languages = []
for num in lang_nums:
try:
idx = int(num) - 1
if 0 <= idx < len(available_langs):
languages.append(f"- {available_langs[idx][1]}")
elif int(num) == other_num:
other_lang = _resume_or_ask(progress, prog_file, 'other_lang',
'Other language', read_input, "Enter language name")
if other_lang:
languages.append(f"- {other_lang}")
except ValueError:
pass
languages_str = '\n'.join(languages) if languages else "- (None specified)"
available_strats = get_available_strategies()
max_strat = len(available_strats)
# Default to 'interview' strategy if available, otherwise first
default_strat_num = "1"
for i, (stem, _) in enumerate(available_strats, 1):
if stem.lower() == "interview":
default_strat_num = str(i)
break
if 'strat_selection' not in progress:
if max_strat == 0:
warn("No strategy files found in strategies/ — defaulting to Interview.")
strat_selection = "1"
else:
print()
print_section("Development Strategy")
info("Select your default development strategy:")
for i, (stem, display) in enumerate(available_strats, 1):
desc = _STRATEGY_DESCRIPTIONS.get(stem, '')
marker = " ★ RECOMMENDED" if str(i) == default_strat_num else ""
print(f" {i}. {display}{marker}")
if desc:
print(f" {desc}")
print()
info("💡 Strategies can be chained — after one completes, you'll be asked if you want to run another.")
while True:
strat_selection = read_input("Selection", default_strat_num)
if not strat_selection.strip():
strat_selection = default_strat_num
break
try:
num = int(strat_selection.strip())
if 1 <= num <= max_strat:
break
except ValueError:
pass
print_error(f"Please enter a number between 1 and {max_strat}.")
progress['strat_selection'] = strat_selection
_save_progress(prog_file, progress)
else:
strat_selection = progress['strat_selection']
info(f" [resumed] Strategy: {strat_selection}")
try:
strat_idx = int(strat_selection.strip()) - 1
if 0 <= strat_idx < len(available_strats):
selected_strategy = available_strats[strat_idx]
else:
selected_strategy = available_strats[0] if available_strats else ("interview", "Interview")
except ValueError:
selected_strategy = available_strats[0] if available_strats else ("interview", "Interview")
strategy_stem, strategy_display = selected_strategy
showed_custom_rules_header = 'has_custom_rules' not in progress
if 'has_custom_rules' not in progress:
print()
print_section("Custom Rules")
info("Add rules the AI must always follow (optional). Enter one rule per line, empty line to finish.")
has_rules = read_yn("Do you have custom rules to add?")
progress['has_custom_rules'] = has_rules
_save_progress(prog_file, progress)
else:
has_rules = progress['has_custom_rules']
if 'custom_rules' not in progress:
if has_rules:
if not showed_custom_rules_header:
print()
print_section("Custom Rules")
info("Continuing rule collection (interrupted mid-loop). Empty line to finish.")
print()
rules_list = list(progress.get('custom_rules_wip', []))
if rules_list:
info(f" [resumed] {len(rules_list)} rule(s) already collected:")
for r in rules_list:
info(f" {r}")
while True:
rule = read_input(" Rule (or Enter to finish)")
if not rule.strip():
break
rules_list.append(f"- {rule.strip().lstrip('- ').strip()}")
progress['custom_rules_wip'] = rules_list
_save_progress(prog_file, progress)
custom_rules = '\n'.join(rules_list) if rules_list else ""
else:
custom_rules = ""
progress['custom_rules'] = custom_rules
progress.pop('custom_rules_wip', None)
_save_progress(prog_file, progress)
else:
custom_rules = progress['custom_rules']
display = custom_rules.replace('\n', '; ')
info(f" [resumed] Custom rules: {display[:60] + '...' if len(custom_rules) > 60 else display or '(none)'}")
if any(k not in progress for k in ('use_soul', 'use_morals', 'use_code_field')):
print()
print_section("Meta Guidelines")
info("Deft ships three meta-guidelines that shape how the AI behaves. All are included")
info("by default — press Enter to keep each, or n to drop it.")
print()
info("SOUL.md — Results-first agent persona (inspired by Winston Wolf).")
info(" Enforces assess-before-acting, finish-what-you-start, right-tool-for-the-job,")
info(" and play-the-long-game. Keeps the AI decisive and concise rather than narrating")
info(" every step. Includes a named persona ('Vinston') — drop if you prefer to define")
info(" your own agent personality.")
print()
info("morals.md — Epistemic honesty rules.")
info(" No presenting speculation as fact, label unverified claims, self-correct when")
info(" wrong. Foundational trust rules for any AI agent. Strongly recommended.")
print()
info("code-field.md — Pre-code assumption protocol.")
info(" Requires stating assumptions, naming failure modes, and writing only code the AI")
info(" can defend — before writing a single line. Fights the 'it compiles, ship it'")
info(" instinct. Based on the NeoVertex1 context-field framework.")
print()
use_soul = _resume_or_ask(progress, prog_file, 'use_soul', 'SOUL.md',
read_yn, "Include meta/SOUL.md? (Results-first persona)", default=True)
use_morals = _resume_or_ask(progress, prog_file, 'use_morals', 'morals.md',
read_yn, "Include meta/morals.md? (Epistemic honesty rules)", default=True)
use_code_field = _resume_or_ask(progress, prog_file, 'use_code_field', 'code-field.md',
read_yn, "Include meta/code-field.md? (Pre-code assumption protocol)", default=True)
# Build experimental rules section
experimental_rules = []
if use_soul:
experimental_rules.append("- ! Use meta/SOUL.md for strategic context and purpose-driven guidance")
if use_morals:
experimental_rules.append("- ! Use meta/morals.md for ethical AI development principles")
if use_code_field:
experimental_rules.append("- ~ Use meta/code-field.md for advanced architecture patterns")
experimental_section = ""
if experimental_rules:
experimental_section = "\n## Experimental Rules\n\n" + "\n".join(experimental_rules)
# Build coverage override line (only if non-default)
coverage_line = f"\n**Coverage**: ! ≥{coverage}% test coverage" if coverage != "85" else ""
# Build strategy line (omit link when no strategy files exist)
if available_strats:
strategy_line = f"**Default Strategy**: [{strategy_display}](../strategies/{strategy_stem}.md)"
else:
strategy_line = f"**Default Strategy**: {strategy_display}"
# Generate user.md
user_content = f"""# User Preferences
Legend (from RFC2119): !=MUST, ~=SHOULD, ≉=SHOULD NOT, ⊗=MUST NOT, ?=MAY.
## Personal (always wins)
Settings in this section have HIGHEST precedence — override all other deft rules,
including PROJECT.md.
**Name**: Address the user as: **{user_name}**
**Custom Rules**:
{custom_rules if custom_rules else "No custom rules defined yet."}
## Defaults (fallback)
Settings in this section are fallback defaults. PROJECT.md overrides these
for project-scoped settings (strategy, coverage, languages).
**Primary Languages**:
{languages_str}
{strategy_line}
{coverage_line}
{experimental_section}
---
**Note**: You can edit this file anytime to update your preferences.
**See**: [../main.md](../main.md) for framework defaults.
"""
_atomic_write(user_file, user_content)
_clear_progress(prog_file)
success(f"Created user.md at {user_file}")
print()
info("user.md defines your personal preferences and default standards.")
print()
# Always offer to configure project settings
print()
print_section("Next Steps")
if read_yn("Would you like to run 'run project' now?", default=True):
print()
return cmd_project([])
else:
print()
info("You can run 'run project' later to configure your project")
return 0
def cmd_project(args: List[str]):
"""Project command - configure project.md"""
print_header(f"Deft CLI v{VERSION} - Project Configuration")
print()
info("This command creates project.md, which defines YOUR project's specifics:")
info(" • Tech stack and programming language")
info(" • Project type (CLI, API, Web App, Library, etc.)")
info(" • Quality standards (test coverage thresholds)")
info(" • Workflow commands (task check, task test, etc.)")
print()
info("This file tells AI assistants how to build and maintain YOUR project.")
info("It works alongside the general Deft guidelines in ./deft/")
print()
defaults = get_default_paths()
# Resume support (issue #8)
prog_file = _progress_path(resolve_path(defaults['project']))
progress = {}
if prog_file.exists():
saved = _load_progress(prog_file)
if saved:
print_section("Previous Session Found")
for k, v in saved.items():
if not k.startswith('_'):
info(f" {k}: {v}")
print()
if read_yn("Resume where you left off?", default=True):
progress = saved
else:
_clear_progress(prog_file)
# Check if we're in a project directory
if not Path("./deft").is_dir():
warn("No ./deft directory found. Run 'run install' first or specify a project directory.")
if read_yn("Install deft in current directory?"):
return cmd_install(["."])
else:
return 1
if 'output_path' not in progress:
print_section("Output Location")
project_path_str = _resume_or_ask(progress, prog_file, 'output_path', 'Output',
read_input, "Where to write PROJECT.md", defaults['project'])
project_file = resolve_path(project_path_str)
# Gather project information
dir_default = Path.cwd().name
project_name = _resume_or_ask(progress, prog_file, 'project_name', 'Project',
read_input, "Project name", dir_default)
type_map = {
"1": "CLI",
"2": "TUI",
"3": "REST API",
"4": "Web App",
"5": "Library",
"6": "Other"
}
valid_type_nums = set(type_map.keys())
if 'type_selection' not in progress:
print()
info("Select project type (comma-separated if multiple):")
print(" 1. CLI (Command-line interface)")
print(" 2. TUI (Terminal UI)")
print(" 3. REST API")
print(" 4. Web App")
print(" 5. Library")
print(" 6. Other")
while True:
type_selection = read_input("Selection")
if not type_selection.strip():
print_error("Please enter at least one selection (1-6).")
continue
nums = [s.strip() for s in type_selection.split(',')]
if len(nums) != len(set(nums)):
print_error("Duplicate selections are not allowed.")
continue
if all(n in valid_type_nums for n in nums):
break
print_error("Please enter numbers between 1 and 6 (comma-separated).")
progress['type_selection'] = type_selection
_save_progress(prog_file, progress)
else:
type_selection = progress['type_selection']
info(f" [resumed] Type: {type_selection}")
type_nums = [s.strip() for s in type_selection.split(',')]
project_types = []
custom_type = ""
for num in type_nums:
if num == "6":
custom_type = _resume_or_ask(progress, prog_file, 'custom_type', 'Custom type',
read_input, "Enter custom project type")
project_types.append(custom_type)
elif num in type_map:
project_types.append(type_map[num])
project_types_str = ", ".join(project_types)
# Read USER.md defaults to avoid re-asking questions already answered
# during bootstrap (fix for #7 — double prompting)
user_defaults = _read_user_defaults(defaults)
# Language selection — pre-fill from USER.md if available
available_langs = get_available_languages()
other_num = len(available_langs) + 1
valid_lang_nums = set(str(i) for i in range(1, other_num + 1))
if 'lang_selection' not in progress:
print()
if user_defaults.get('languages'):
user_lang_names = user_defaults['languages']
user_lang_display = ', '.join(user_lang_names)
info(f"Languages from USER.md: {user_lang_display}")
info("Select primary programming language(s) (comma-separated):")
for i, (stem, display) in enumerate(available_langs, 1):
print(f" {i}. {display}")
print(f" {other_num}. Other")
while True:
lang_selection = read_input(
f"Selection, or Enter to keep [{user_lang_display}]", ""
)
if not lang_selection.strip():
break # Accept USER.md defaults
nums = [s.strip() for s in lang_selection.split(',')]
if len(nums) != len(set(nums)):
print_error("Duplicate selections are not allowed.")
continue
if all(n in valid_lang_nums for n in nums):
break
print_error(f"Please enter numbers between 1 and {other_num} (comma-separated).")
else:
info("Select primary programming language(s) (comma-separated):")
for i, (stem, display) in enumerate(available_langs, 1):
print(f" {i}. {display}")
print(f" {other_num}. Other")
while True:
lang_selection = read_input("Selection (e.g., 1,3)")
if not lang_selection.strip():
break # Skip (falls through to Python default)
nums = [s.strip() for s in lang_selection.split(',')]
if len(nums) != len(set(nums)):
print_error("Duplicate selections are not allowed.")
continue
if all(n in valid_lang_nums for n in nums):
break
print_error(f"Please enter numbers between 1 and {other_num} (comma-separated).")
progress['lang_selection'] = lang_selection
progress['_had_user_lang_defaults'] = bool(user_defaults.get('languages'))
_save_progress(prog_file, progress)
else:
lang_selection = progress['lang_selection']
info(f" [resumed] Languages: {lang_selection or '(USER.md defaults)'}")
# Parse language selection
has_user_lang_defaults = user_defaults.get('languages') or progress.get('_had_user_lang_defaults')
if not lang_selection.strip() and has_user_lang_defaults:
# Accept USER.md defaults
user_lang_names = user_defaults.get('languages', [])
selected_langs = []
for lang_name in user_lang_names:
matched = False
for stem, display in available_langs:
if display.lower() == lang_name.lower():
selected_langs.append((stem, display))
matched = True
break
if not matched:
selected_langs.append((lang_name.lower(), lang_name))
if not selected_langs:
selected_langs = [("python", "Python")]
else:
lang_nums = [s.strip() for s in lang_selection.split(',')]
selected_langs = []
for num in lang_nums:
try:
idx = int(num) - 1
if 0 <= idx < len(available_langs):
selected_langs.append(available_langs[idx])
elif int(num) == other_num:
other_lang = _resume_or_ask(progress, prog_file, 'other_lang',
'Other language', read_input, "Enter language name")
if other_lang:
selected_langs.append((other_lang.lower(), other_lang))
except ValueError:
pass
if not selected_langs:
selected_langs = [("python", "Python")]