-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
341 lines (273 loc) · 10.3 KB
/
Copy pathcli.py
File metadata and controls
341 lines (273 loc) · 10.3 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
import sys
import ast
from rich.console import Console
from config import WORKSPACE_DIR, MAX_LLM_CALLS
from agent.normalize import normalize_command
from agent.cache import (
load_cached_hybrid,
save_cached_hybrid,
load_last_good,
)
from agent.engine import ForgePilotEngine
from agent.generator import generate_project
from agent.validator import run_validation
from agent.budget import LLMBudget
from agent.operations import apply_operations
from agent.git_rollback import rollback_last_change
from agent.workspace import (
list_workspace_files,
get_workspace_snapshot,
clear_workspace,
)
console = Console()
# ----------------------------
# Utilities
# ----------------------------
def write_files(files: dict):
"""
Replace workspace contents with the generated file set
using the shared operation safety layer.
"""
clear_workspace()
operations = [
{
"type": "write_file",
"path": filename,
"content": content,
}
for filename, content in files.items()
]
apply_operations(operations)
for filename in files:
console.print(
f"[green]✓ wrote[/green] {filename}"
)
def validate_result_structure(result: dict, phase: str):
"""
Ensure LLM output has the expected structure.
"""
if not isinstance(result, dict):
raise RuntimeError(f"{phase}: result is not a dict")
if "files" not in result:
raise RuntimeError(f"{phase}: missing top-level key 'files'")
if not isinstance(result["files"], dict):
raise RuntimeError(f"{phase}: 'files' must be a dict")
if not result["files"]:
raise RuntimeError(f"{phase}: 'files' must not be empty")
# ----------------------------
# Main Orchestration
# ----------------------------
def main():
if len(sys.argv) < 2:
console.print(
"[red]Error:[/red] Please provide a command.\n"
"Example:\n"
' python cli.py "Build a CLI that converts temperatures"\n'
' python cli.py --new-project "Build a Snake game"'
)
sys.exit(1)
new_project = sys.argv[1] == "--new-project"
if new_project:
if len(sys.argv) < 3:
console.print(
"[red]Error:[/red] --new-project requires a goal."
)
sys.exit(1)
goal = sys.argv[2]
else:
goal = sys.argv[1]
if normalize_command(goal) == "rollback":
try:
commit = rollback_last_change()
console.print(
"[bold green]✓ Last ForgePilot change rolled back[/bold green]"
)
console.print(
f"[dim]Rollback commit: {commit[:8]}[/dim]"
)
except Exception as e:
console.print(
f"[bold red]Rollback failed:[/bold red] {e}"
)
return
normalized = normalize_command(goal)
budget = LLMBudget(MAX_LLM_CALLS)
workspace_files = list_workspace_files()
if new_project:
console.rule("[bold yellow]New Project[/bold yellow]")
console.print(
"[yellow]Creating a new project from a clean workspace[/yellow]"
)
console.rule("[bold blue]AI Cursor Agent")
console.print(f"[bold]Goal:[/bold] {goal}")
console.print(f"[dim]Normalized:[/dim] {normalized}")
console.print(f"[dim]LLM budget:[/dim] {budget.remaining}")
# ----------------------------
# Cache Lookup
# ----------------------------
cached = None
cache_type = None
# Cached entries are complete generated projects, and replaying one
# clears the workspace. Only consult the cache when there is no
# existing project to overwrite.
if not new_project and not workspace_files:
cached, cache_type = load_cached_hybrid(normalized)
if cached is not None:
if cache_type == "exact":
console.print("[green]✓ Exact cache hit[/green]")
result = ast.literal_eval(cached)
write_files(result["files"])
console.print("[bold green]Done (no LLM calls used)[/bold green]")
return
elif cache_type == "semantic":
console.print("[green]✓ Semantic cache candidate found[/green]")
result = ast.literal_eval(cached)
write_files(result["files"])
ok, err = run_validation()
if ok:
console.print("[bold green]✓ Semantic cache validated[/bold green]")
console.print("[bold green]Done (no LLM calls used)[/bold green]")
return
console.print("[yellow]Semantic cache candidate failed validation[/yellow]")
if not new_project and not workspace_files:
console.print("[yellow]Cache miss — generating project[/yellow]")
# ----------------------------
# Generation / Coding Agent Phase
# ----------------------------
if new_project or workspace_files:
# ========================================================
# NEW OR EXISTING PROJECT → AUTONOMOUS CODING ENGINE
#
# The engine owns the task checkpoint, so a failed
# --new-project run restores the previous project.
# ========================================================
console.rule(
"[bold yellow]ForgePilot Autonomous Engine[/bold yellow]"
)
if not new_project:
console.print(
f"[cyan]Existing workspace detected: "
f"{len(workspace_files)} files[/cyan]"
)
try:
engine = ForgePilotEngine(
budget=budget,
max_repair_attempts=3,
new_project=new_project,
)
result = engine.run(goal)
if result["status"] == "verified":
console.print(
"[bold green]✓ ForgePilot verified the changes[/bold green]"
)
console.print(
f"[dim]Repair attempts: "
f"{result['repair_attempts']}[/dim]"
)
console.print(
f"[dim]Validation attempts: "
f"{result['validation_attempts']}[/dim]"
)
context_available = result["context_chars_available"]
context_selected = result["context_chars_selected"]
reduction = (
(1 - context_selected / context_available) * 100
if context_available
else 0.0
)
console.print("[dim]Context:[/dim]")
console.print(
f"[dim] Files: "
f"{result['context_files_selected']}/"
f"{result['context_files_available']}[/dim]"
)
console.print(
f"[dim] Chunks: "
f"{result['context_chunks_selected']}/"
f"{result['context_chunks_available']}[/dim]"
)
console.print(
f"[dim] Characters: "
f"{context_selected:,}/"
f"{context_available:,}[/dim]"
)
console.print(
f"[dim] Reduction: {reduction:.1f}%[/dim]"
)
if new_project:
save_cached_hybrid(
normalized,
str({"files": get_workspace_snapshot()}),
validated=True,
)
else:
console.print(
"[bold red]✗ ForgePilot could not verify the changes[/bold red]"
)
console.print(
"[yellow]↩ Workspace restored to pre-task state[/yellow]"
)
console.print(
f"[dim]Repair attempts: "
f"{result['repair_attempts']}[/dim]"
)
console.print(
f"[dim]Validation attempts: "
f"{result['validation_attempts']}[/dim]"
)
console.print(
f"[red]{result['error']}[/red]"
)
except Exception as e:
console.print(
f"[bold red]ForgePilot engine failed:[/bold red] {e}"
)
return
else:
# ========================================================
# EMPTY PROJECT → PROJECT GENERATOR
# ========================================================
console.rule("[bold yellow]LLM Generation[/bold yellow]")
try:
console.print(f"Remaining LLM budget: {budget.remaining}")
result = generate_project(goal, budget,)
validate_result_structure(result, "Generation")
write_files(
result["files"]
)
except Exception as e:
console.print(f"[bold red]Generation failed:[/bold red] {e}")
return
# ----------------------------
# Validation Phase
# ----------------------------
console.rule("[bold magenta]Validation (pytest)")
ok, err = run_validation()
if ok:
console.print("[bold green]✓ Validation passed[/bold green]")
if not workspace_files:
workspace = get_workspace_snapshot()
save_cached_hybrid(
normalized,
str({"files": workspace,}),
validated=True,
)
console.print("[green]✓ Cached result and saved as last-known-good[/green]")
return
console.rule("[bold red]Validation Failed")
console.print(err)
# ----------------------------
# Fallback: Last Known Good
# ----------------------------
if not workspace_files:
console.rule("[bold yellow]Fallback[/bold yellow]")
fallback = load_last_good(normalized)
if fallback:
console.print("[yellow]Restoring last-known-good output[/yellow]")
result = ast.literal_eval(fallback)
write_files(result["files"])
console.print("[green]✓ Restored last-known-good project[/green]")
else:
console.print("[red]No last-known-good output available[/red]")
if __name__ == "__main__":
main()