-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathJForgeAgent.java
More file actions
1983 lines (1723 loc) · 91.1 KB
/
JForgeAgent.java
File metadata and controls
1983 lines (1723 loc) · 91.1 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 jbang "$0" "$@" ; exit $?
//JAVA 26+
//DEPS com.google.adk:google-adk:1.0.0-rc.1
//DEPS org.slf4j:slf4j-simple:2.0.12
//DEPS info.picocli:picocli:4.7.5
//DEPS com.google.code.gson:gson:2.10.1
import com.google.adk.agents.LlmAgent;
import com.google.adk.runner.InMemoryRunner;
import com.google.adk.sessions.SessionKey;
import com.google.adk.tools.GoogleSearchTool;
import com.google.genai.types.Content;
import com.google.genai.types.Part;
import java.io.Console;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import static picocli.CommandLine.Help.Ansi.AUTO;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
@Command(name = "jforge", mixinStandardHelpOptions = true, version = "JForge V1.0", description = "Tool Orchestrator - Autonomous Java Agent", headerHeading = "@|bold,underline Usage|@:%n%n", descriptionHeading = "%n@|bold,underline Description|@:%n%n", optionListHeading = "%n@|bold,underline Options|@:%n")
public class JForgeAgent implements Callable<Integer> {
// ==================== CONSTANTS ====================
private static final Path TOOLS_DIR = Path.of("tools");
private static final Path LOGS_DIR = Path.of("logs");
private static final Path WORKFLOWS_DIR = Path.of("workflows");
private static final Path ARTIFACTS_DIR = Path.of("artifacts");
private static final Path PRODUCTS_DIR = Path.of("products");
private static final Path MEMORY_DIR = Path.of("memory");
private static final Path MEMORY_FILE = MEMORY_DIR.resolve("context.json");
private static final String PRE_SUPERVISOR = "@|bold,cyan [SUPERVISOR] ";
private static final String PRE_ROUTER = "@|bold,blue [ROUTER] ";
private static final String PRE_CODER = "@|bold,magenta [CODER] ";
private static final String PRE_TESTER = "@|bold,cyan [TESTER] ";
private static final String PRE_EXECUTOR = "@|bold,blue [EXECUTOR] ";
private static final int MAX_MEMORY_ENTRIES = 20; // kept internal — not user-tunable
private static final int MAX_HISTORY_CHARS = 2000;
private static final int MAX_LOOP_ITERATIONS = 10;
private static final int MAX_SEARCH_PER_DEMAND = 3;
private static final int MAX_TOOL_TIMEOUT_SECONDS = 120;
private static final int MAX_REPLANS = 2;
private static final int MAX_CRASH_RETRIES = 3; // abort after 3 failures (2 repair attempts)
private static final int MAX_WORKFLOWS_IN_CONTEXT = 3; // workflows shown in Supervisor prompt (keep small)
// ==================== CLI OPTIONS ====================
@CommandLine.Option(names = {
"--supervisor-model" }, description = "Gemini model for the Supervisor agent", defaultValue = "gemini-3-pro-preview", showDefaultValue = CommandLine.Help.Visibility.ALWAYS)
private String supervisorModel = "gemini-3-pro-preview";
@CommandLine.Option(names = {
"--router-model" }, description = "Gemini model for the Router agent", defaultValue = "gemini-3-pro-preview", showDefaultValue = CommandLine.Help.Visibility.ALWAYS)
private String routerModel = "gemini-3-pro-preview";
@CommandLine.Option(names = {
"--coder-model" }, description = "Gemini model for the Coder agent", defaultValue = "gemini-3-pro-preview", showDefaultValue = CommandLine.Help.Visibility.ALWAYS)
private String coderModel = "gemini-3-pro-preview";
@CommandLine.Option(names = {
"--assistant-model" }, description = "Gemini model for the Assistant agent", defaultValue = "gemini-3.1-flash-lite-preview", showDefaultValue = CommandLine.Help.Visibility.ALWAYS)
private String assistantModel = "gemini-3.1-flash-lite-preview";
@CommandLine.Option(names = {
"--searcher-model" }, description = "Gemini model for the Searcher agent", defaultValue = "gemini-3.1-flash-lite-preview", showDefaultValue = CommandLine.Help.Visibility.ALWAYS)
private String searcherModel = "gemini-3.1-flash-lite-preview";
@CommandLine.Option(names = {
"--tester-model" }, description = "Gemini model for the Tester agent", defaultValue = "gemini-3.1-flash-lite-preview", showDefaultValue = CommandLine.Help.Visibility.ALWAYS)
private String testerModel = "gemini-3.1-flash-lite-preview";
@CommandLine.Option(names = {
"--max-tools" }, description = "Maximum number of cached tools before GC eviction (default: 10)", defaultValue = "10")
private int maxTools = 10;
@CommandLine.Option(names = {
"--tool-age-days" }, description = "Days before an unused tool is eligible for GC deletion (default: 30)", defaultValue = "30")
private long maxToolAgeDays = 30;
@CommandLine.Option(names = {
"--prompt" }, description = "Run a single prompt non-interactively and exit (CI/CD/pipe mode)")
private String promptFlag;
@CommandLine.Option(names = {
"--skip-test" }, description = "Skip automatic test after CREATE (use for GUI/Swing or hardware-dependent tools)", defaultValue = "false")
private boolean skipTest = false;
@CommandLine.Option(names = {
"--silent" }, description = "Suppress all status/decorative output; print only the final result (for pipe/MCP/A2A use)", defaultValue = "false")
private boolean silent = false;
@CommandLine.Option(names = {
"--max-workflows" }, description = "Maximum number of cached workflows before GC eviction (default: 10)", defaultValue = "10")
private int maxWorkflows = 10;
@CommandLine.Option(names = {
"--workflow-age-days" }, description = "Days before an unused workflow is eligible for GC deletion (default: 30)", defaultValue = "30")
private long maxWorkflowAgeDays = 30;
/**
* Sort paths by last-modified time descending; IOException -> tie (unreadable
* mtime).
*/
private static final Comparator<Path> BY_MTIME_DESC = (p1, p2) -> {
try {
return Files.getLastModifiedTime(p2).compareTo(Files.getLastModifiedTime(p1));
} catch (IOException e) {
return 0;
}
};
/**
* OS-specific system/hidden files that the guardrail must never move to
* products/.
* Covers Windows (Thumbs.db, desktop.ini) and any future platform artefacts.
*/
private static final Set<String> GUARDRAIL_IGNORED_FILES = Set.of(
"thumbs.db", "desktop.ini", "ehthumbs.db", "ehthumbs_vista.db");
/**
* JVM/jbang flag prefixes that the LLM must not inject into script arguments.
*/
private static final List<String> BLOCKED_ARG_PREFIXES = List.of("-D", "-X", "--classpath", "--deps",
"--jvm-options",
"--", "-agent", "--source"); // "--" ends jbang flags; "-agent" loads JVM agents; "--source" redirects
// compilation
/**
* Pre-compiled once; used in isToolNameSafe() on every tool name validation.
*/
private static final java.util.regex.Pattern SAFE_TOOL_NAME = java.util.regex.Pattern
.compile("[A-Za-z0-9_\\-]+\\.java");
private static final DateTimeFormatter FMT_CLOCK = DateTimeFormatter.ofPattern("EEEE, dd MMMM yyyy HH:mm:ss");
private static final DateTimeFormatter FMT_LOG_TS = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
/** Workspace topology — computed once; paths are static final and immutable. */
private static final String WORKSPACE_TOPOLOGY = String.format(
"""
Workspace Architecture (Absolute Paths):
- TOOLS: %s
- LOGS: %s
- ARTIFACTS: %s (Instruct tools to use this EXACT ABSOLUTE PATH for temporary data and extractions)
- PRODUCTS: %s (Instruct tools to save user-requested final files using this EXACT ABSOLUTE PATH)
MANDATORY RULE: When creating tools that write files, you MUST feed them the literal absolute path strings above. Do not use relative paths like '/products'.
""",
TOOLS_DIR.toAbsolutePath().toString().replace("\\", "/"),
LOGS_DIR.toAbsolutePath().toString().replace("\\", "/"),
ARTIFACTS_DIR.toAbsolutePath().toString().replace("\\", "/"),
PRODUCTS_DIR.toAbsolutePath().toString().replace("\\", "/"));
// ==================== FIELDS ====================
private Path currentSessionLog;
private long lastGcRun = 0; // throttle: prevents redundant filesystem scans within the same minute
private final Deque<String> conversationMemory = new ArrayDeque<>();
/** Captures the last result text when running in --silent / machine mode. */
private final StringBuilder resultBuffer = new StringBuilder();
private Agent supervisor;
private Agent router;
private Agent coder;
private Agent assistant;
private Agent searcher;
private Agent tester;
// ==================== ENTRY POINT ====================
public static void main(String[] args) {
System.setProperty("picocli.ansi", "true");
int exitCode = new CommandLine(new JForgeAgent()).execute(args);
System.exit(exitCode);
}
// ==================== MAIN CICLE ====================
@Override
public Integer call() throws Exception {
String apiKey = System.getenv("GEMINI_API_KEY");
if (apiKey == null || apiKey.isBlank()) {
System.err.println(AUTO.string("@|bold,red \u274C Please set the GEMINI_API_KEY environment variable.|@"));
return 1;
}
// Required by google-adk
System.setProperty("GOOGLE_API_KEY", apiKey);
Files.createDirectories(TOOLS_DIR);
Files.createDirectories(LOGS_DIR);
Files.createDirectories(WORKFLOWS_DIR);
Files.createDirectories(ARTIFACTS_DIR);
Files.createDirectories(PRODUCTS_DIR);
Files.createDirectories(MEMORY_DIR);
initLogging();
// Route ADK's SLF4J output into our session log — must be set before first
// SLF4J use (SimpleLoggerFactory initialises lazily, so this window is safe).
System.setProperty("org.slf4j.simpleLogger.logFile", currentSessionLog.toAbsolutePath().toString());
System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "warn");
System.setProperty("org.slf4j.simpleLogger.showDateTime", "true");
System.setProperty("org.slf4j.simpleLogger.dateTimeFormat", "HH:mm:ss");
System.setProperty("org.slf4j.simpleLogger.showLogName", "false");
System.setProperty("org.slf4j.simpleLogger.showThreadName", "false");
System.setProperty("org.slf4j.simpleLogger.levelInBrackets", "true");
loadMemory();
supervisor = new Agent("supervisor", supervisorModel, SUPERVISOR_INSTRUCTION);
router = new Agent("router", routerModel, ROUTER_INSTRUCTION);
coder = new Agent("coder", coderModel, CODER_INSTRUCTION);
assistant = new Agent("assistant", assistantModel, ASSISTANT_INSTRUCTION);
searcher = new Agent("searcher", searcherModel, SEARCHER_INSTRUCTION, new GoogleSearchTool());
tester = new Agent("tester", testerModel, TESTER_INSTRUCTION);
status("@|faint [LLM] supervisor [" + supervisorModel + "] router [" + routerModel + "] coder [" + coderModel
+ "]|@");
status("@|faint [LLM] assistant [" + assistantModel + "] searcher [" + searcherModel + "] tester ["
+ testerModel + "]|@");
if (promptFlag != null && !promptFlag.isBlank()) {
if (!silent)
printWelcome();
runGarbageCollector();
logToFile("[USER] " + promptFlag);
processDemand(promptFlag);
} else {
startChatMenu();
}
return 0;
}
private void printWelcome() {
status("@|bold,cyan Welcome to JForge V1.0 - Tool Orchestrator.|@");
status("Available tools are cached in: @|yellow " + TOOLS_DIR.toAbsolutePath() + "|@");
status("Logs are recorded in: @|yellow " + LOGS_DIR.toAbsolutePath() + "|@");
status("Workflow patterns stored in: @|yellow " + WORKFLOWS_DIR.toAbsolutePath() + "|@");
status("Workspace [Products]: @|yellow " + PRODUCTS_DIR.toAbsolutePath() + "|@");
status("Workspace [Artifacts]: @|yellow " + ARTIFACTS_DIR.toAbsolutePath() + "|@\n");
}
// ==================== LOGGING ====================
private void initLogging() {
String timestamp = LocalDateTime.now().format(FMT_LOG_TS);
this.currentSessionLog = LOGS_DIR.resolve("session_" + timestamp + ".log");
logToFile("==== JForgeAgent Orchestration Lifecycle Started ====");
rotateLogs();
}
private void logToFile(String message) {
if (this.currentSessionLog == null)
return;
try {
Files.writeString(this.currentSessionLog, message + "\n", StandardOpenOption.CREATE,
StandardOpenOption.APPEND);
} catch (IOException e) {
System.err.println("[LOG ERROR] Could not write to session log: " + e.getMessage());
}
}
private void addToMemory(String entry) {
if (conversationMemory.size() >= MAX_MEMORY_ENTRIES) {
conversationMemory.pollFirst();
}
conversationMemory.addLast(entry);
saveMemory();
}
private void loadMemory() {
if (!Files.exists(MEMORY_FILE))
return;
try {
List<String> lines = Files.readAllLines(MEMORY_FILE);
int start = Math.max(0, lines.size() - MAX_MEMORY_ENTRIES);
lines.subList(start, lines.size()).forEach(conversationMemory::addLast);
logToFile("[MEMORY] Loaded " + (lines.size() - start) + " entries from persistent memory.");
} catch (Exception e) {
logToFile("[WARN] Could not load memory file — starting empty: " + e.getMessage());
}
}
private void saveMemory() {
try {
Files.write(MEMORY_FILE, new ArrayList<>(conversationMemory));
} catch (Exception e) {
logToFile("[WARN] Could not persist memory: " + e.getMessage());
}
}
private void rotateLogs() {
try (Stream<Path> stream = Files.list(LOGS_DIR)) {
stream.filter(p -> p.toString().endsWith(".log"))
.sorted(BY_MTIME_DESC)
.skip(3)
.forEach(p -> {
try {
Files.deleteIfExists(p);
} catch (IOException e) {
System.err.println(
"[LOG ROTATE ERROR] Could not delete " + p.getFileName() + ": " + e.getMessage());
}
});
} catch (IOException e) {
System.err.println("[LOG ROTATE ERROR] Could not list logs directory: " + e.getMessage());
}
}
// ==================== SUPERVISOR WORKFLOW ====================
/**
* Main orchestration path: the Supervisor decomposes the user goal into a
* WorkflowPlan and the WorkflowExecutor runs it. On failure the Supervisor
* is asked to replan (max {@code MAX_REPLANS} times). If the plan cannot be
* parsed at all, falls back to the legacy Router loop.
*/
private void supervisorWorkflow(String userPrompt) throws Exception {
status(PRE_SUPERVISOR + "Decomposing goal into workflow...|@");
LoopState state = new LoopState();
String timestamp = LocalDateTime.now().format(FMT_LOG_TS);
String rawJson = supervisor.invoke(buildSupervisorPrompt(userPrompt, state));
WorkflowPlan plan = parseWorkflowPlan(rawJson);
// Parse the supervisor response once for whitespace-safe type detection
JsonObject rawParsed = null;
try {
rawParsed = new Gson().fromJson(extractJsonBlock(rawJson), JsonObject.class);
} catch (Exception ignored) {
}
String responseType = rawParsed != null ? jsonStr(rawParsed, "type", "") : "";
// REUSE: Supervisor matched a stored workflow — skip planning, load from disk
if ("REUSE".equals(responseType)) {
try {
String id = jsonStr(rawParsed, "id", "");
if (id.isBlank())
throw new IllegalStateException("REUSE response missing 'id'");
WorkflowPlan reused = loadWorkflowById(id);
if (reused != null && !reused.steps().isEmpty()) {
status(PRE_SUPERVISOR + "Reusing stored workflow: |@" + id);
logToFile("[SUPERVISOR] REUSE → " + id);
plan = reused;
// skip saveWorkflowPlan — plan already persisted
logToFile("[SUPERVISOR] Plan '" + plan.goal() + "' | " + plan.steps().size() + " steps");
status(PRE_SUPERVISOR + plan.steps().size() + " steps planned for: "
+ truncate(plan.goal(), 80) + "|@");
runWorkflowPlan(plan, state, userPrompt);
return;
}
logToFile("[SUPERVISOR] REUSE target not found (" + id + ") — falling back to new plan.");
} catch (Exception e) {
logToFile("[WARN] REUSE parse failed: " + e.getMessage() + " — continuing with new plan.");
}
}
// SIMPLE bypass: Supervisor decided no planning overhead is needed
if (plan != null && plan.isSimple()) {
status(PRE_SUPERVISOR + "Simple request — bypassing plan, routing directly.|@");
logToFile("[SUPERVISOR] SIMPLE bypass → processDemandRouter.");
processDemandRouter(userPrompt);
return;
}
saveWorkflowPlan(rawJson, timestamp, "");
if (plan == null || plan.steps().isEmpty()) {
status("@|bold,yellow [SUPERVISOR] No valid plan produced — falling back to Router mode.|@");
logToFile("[SUPERVISOR] Plan parse failed — delegating to processDemandRouter.");
processDemandRouter(userPrompt);
return;
}
logToFile("[SUPERVISOR] Plan '" + plan.goal() + "' | " + plan.steps().size() + " steps");
status(PRE_SUPERVISOR + plan.steps().size() + " steps planned for: "
+ truncate(plan.goal(), 80) + "|@");
runWorkflowPlan(plan, state, userPrompt);
}
/**
* Execute + replan loop shared by the normal WORKFLOW path and the REUSE path.
*/
private void runWorkflowPlan(WorkflowPlan initialPlan, LoopState state, String userPrompt) throws Exception {
// Single-step plans route directly to the Router — no executor overhead needed.
// The Router's own crash-retry loop (MAX_CRASH_RETRIES) handles failures
// internally.
if (initialPlan.steps().size() == 1) {
String stepGoal = initialPlan.steps().get(0).goal();
status(PRE_SUPERVISOR + "Single-step plan — routing directly.|@");
logToFile("[SUPERVISOR] Single-step bypass → processDemandRouter: " + truncate(stepGoal, 120));
processDemandRouter(stepGoal);
addToMemory("USER: " + userPrompt);
addToMemory("SYSTEM (WORKFLOW): " + initialPlan.goal() + " | steps=1");
return;
}
WorkflowPlan plan = initialPlan;
String timestamp = LocalDateTime.now().format(FMT_LOG_TS);
for (int replan = 0; replan <= MAX_REPLANS; replan++) {
boolean ok = new WorkflowExecutor().execute(plan, state);
if (ok) {
addToMemory("USER: " + userPrompt);
addToMemory("SYSTEM (WORKFLOW): " + plan.goal()
+ " | steps=" + plan.steps().size());
break;
}
if (replan == MAX_REPLANS) {
status("@|bold,red [SUPERVISOR] Max replans (" + MAX_REPLANS + ") reached. Aborting.|@");
logToFile("[SUPERVISOR] Max replans exceeded. Last error: " + truncate(state.lastError, 300));
break;
}
status("@|bold,yellow [SUPERVISOR] Replanning (" + (replan + 1) + "/" + MAX_REPLANS
+ ") due to: " + truncate(state.lastError, 80) + "|@");
logToFile("[SUPERVISOR] Replan " + (replan + 1) + ". Error: " + truncate(state.lastError, 200));
String prevError = state.lastError;
state.lastError = null;
String rawJson = supervisor.invoke(buildSupervisorReplanPrompt(userPrompt, plan, prevError, state));
plan = parseWorkflowPlan(rawJson);
saveWorkflowPlan(rawJson, timestamp, "_replan" + (replan + 1));
if (plan == null || plan.steps().isEmpty()) {
status("@|bold,red [SUPERVISOR] Replan produced no valid plan. Aborting.|@");
break;
}
logToFile("[SUPERVISOR] New plan after replan " + (replan + 1)
+ ": " + plan.goal() + " | " + plan.steps().size() + " steps");
}
}
/**
* Persists a successful WorkflowPlan JSON to
* workflows/workflow_<timestamp>.json.
* Replans are saved to logs/ only (debugging), not to workflows/ (not reusable
* patterns).
* When a replan occurs the failure counter in the base workflow's .fail.json
* sidecar
* is incremented so the Supervisor can deprioritise repeatedly-failing
* patterns.
*/
private void saveWorkflowPlan(String rawJson, String timestamp, String suffix) {
if (rawJson == null || rawJson.isBlank())
return;
String json = extractJsonBlock(rawJson);
if (json == null)
json = rawJson;
// Do not persist REUSE meta-responses — they are not workflow plans
try {
JsonObject root = new Gson().fromJson(json, JsonObject.class);
if ("REUSE".equals(jsonStr(root, "type", "")))
return;
} catch (Exception ignored) {
}
// Successful plans go to workflows/ for Supervisor reuse; replans go to logs/
// for debugging
Path dir = suffix.isEmpty() ? WORKFLOWS_DIR : LOGS_DIR;
Path file = dir.resolve("workflow_" + timestamp + suffix + ".json");
try {
Files.writeString(file, json);
logToFile("[SUPERVISOR] Workflow plan saved: " + file);
} catch (IOException e) {
logToFile("[WARN] Could not save workflow plan: " + e.getMessage());
}
// Bump failure counter for the base workflow whenever a replan is triggered
if (!suffix.isEmpty()) {
Path baseFile = WORKFLOWS_DIR.resolve("workflow_" + timestamp + ".json");
bumpWorkflowFailCount(baseFile);
}
}
/**
* Increments the integer stored in {@code workflowFile.fail.json} by 1. Creates
* the sidecar with value 1 if absent.
*/
private void bumpWorkflowFailCount(Path workflowFile) {
Path failFile = WORKFLOWS_DIR.resolve(
workflowFile.getFileName().toString().replace(".json", ".fail.json"));
int count = readWorkflowFailCount(workflowFile);
try {
Files.writeString(failFile, String.valueOf(count + 1));
} catch (IOException e) {
logToFile("[WARN] bumpWorkflowFailCount: " + e.getMessage());
}
}
/**
* Returns the failure count from {@code workflowFile.fail.json}, or 0 if the
* sidecar is absent or unreadable.
*/
private int readWorkflowFailCount(Path workflowFile) {
Path failFile = WORKFLOWS_DIR.resolve(
workflowFile.getFileName().toString().replace(".json", ".fail.json"));
if (!Files.exists(failFile))
return 0;
try {
return Integer.parseInt(Files.readString(failFile).strip());
} catch (Exception e) {
return 0;
}
}
/**
* Reads the last 3 successful workflow plans from workflows/ and returns a
* compact summary for the Supervisor context — goal + step sequence only.
*/
private String loadRecentWorkflows() {
try {
List<Path> files = listArtifactsByMtime(WORKFLOWS_DIR, ".json", MAX_WORKFLOWS_IN_CONTEXT);
if (files.isEmpty())
return "";
var sb = new StringBuilder();
for (Path f : files) {
WorkflowPlan plan = parseWorkflowPlan(Files.readString(f));
if (plan == null || plan.steps().isEmpty())
continue;
sb.append("id: ").append(f.getFileName());
int failCount = readWorkflowFailCount(f);
if (failCount > 0)
sb.append(" [failed ").append(failCount).append("x]");
sb.append("\nGoal: ").append(plan.goal()).append("\n");
sb.append("Steps: ").append(plan.steps().stream()
.map(step -> truncate(step.goal(), 60))
.collect(Collectors.joining(" → ")));
sb.append("\n\n");
}
return sb.toString().strip();
} catch (IOException e) {
logToFile("[WARN] loadRecentWorkflows: " + e.getMessage());
return "";
}
}
/**
* Loads and parses a stored workflow by filename from workflows/. Returns null
* if missing or unparseable.
*/
private WorkflowPlan loadWorkflowById(String id) {
if (id == null || id.isBlank())
return null;
Path file = WORKFLOWS_DIR.resolve(id);
if (!Files.exists(file))
return null;
try {
return parseWorkflowPlan(Files.readString(file));
} catch (IOException e) {
logToFile("[WARN] loadWorkflowById(" + id + "): " + e.getMessage());
return null;
}
}
private String buildSupervisorPrompt(String userGoal, LoopState state) {
if (state.cacheList == null)
state.cacheList = listCachedTools().stream()
.reduce((a, b) -> a + ",\n" + b).orElse("Empty");
String recentWorkflows = loadRecentWorkflows();
return String.format("""
%s
[Recent Successful Workflows]
%s
[Recent Chat History]
%s
User Goal: %s
Classify as SIMPLE, REUSE, or WORKFLOW and respond with JSON.
""",
buildSystemContext(),
recentWorkflows.isEmpty() ? "None" : recentWorkflows,
buildHistory(), userGoal);
}
private String buildSupervisorReplanPrompt(String userGoal, WorkflowPlan failedPlan,
String error, LoopState state) {
String prevSteps = failedPlan.steps().stream()
.map(s -> " " + s.id() + ": " + truncate(s.goal(), 80))
.collect(Collectors.joining("\n"));
return buildSupervisorPrompt(userGoal, state)
+ "\n\nPREVIOUS PLAN FAILED:\n" + prevSteps
+ "\n\nERROR:\n" + error
+ "\n\nGenerate a corrected WorkflowPlan JSON.";
}
/**
* Extracts and parses the JSON WorkflowPlan from a (possibly decorated) LLM
* response.
* Returns null on any parse failure — callers must handle gracefully.
*/
private WorkflowPlan parseWorkflowPlan(String json) {
if (json == null || json.isBlank())
return null;
// Extract the outermost {...} block (LLM may wrap JSON in prose)
String trimmed = extractJsonBlock(json);
if (trimmed == null)
return null;
try {
Gson gson = new Gson();
JsonObject root = gson.fromJson(trimmed, JsonObject.class);
// SIMPLE bypass sentinel
if ("SIMPLE".equals(jsonStr(root, "type", "")))
return new WorkflowPlan("__SIMPLE__", List.of());
String goal = jsonStr(root, "goal", "");
List<WorkflowStep> steps = new ArrayList<>();
if (root.has("steps")) {
JsonArray arr = root.getAsJsonArray("steps");
for (var el : arr) {
JsonObject s = el.getAsJsonObject();
String id = jsonStr(s, "id", "s" + steps.size());
String stepGoal = jsonStr(s, "goal", "");
List<String> dependsOn = new ArrayList<>();
if (s.has("dependsOn"))
for (var d : s.getAsJsonArray("dependsOn"))
dependsOn.add(d.getAsString());
steps.add(new WorkflowStep(id, stepGoal, dependsOn));
}
}
return new WorkflowPlan(goal, steps);
} catch (Exception e) {
logToFile("[SUPERVISOR] WorkflowPlan parse failed: " + e.getMessage()
+ " | JSON: " + truncate(trimmed, 400));
return null;
}
}
/** Null-safe string getter for a JsonObject field with a default value. */
private static String jsonStr(JsonObject obj, String key, String def) {
return (obj.has(key) && !obj.get(key).isJsonNull()) ? obj.get(key).getAsString() : def;
}
// ==================== CHAT MENU ====================
private void startChatMenu() throws Exception {
Console console = System.console();
if (console == null) {
System.err.println(AUTO
.string("@|bold,red \u274C Interactive console is not supported in this environment. Exiting.|@"));
return;
}
printWelcome();
runGarbageCollector();
String inputPrompt = AUTO
.string("@|bold,green \n\uD83E\uDD16 What would you like to achieve? (or 'exit'/'quit'): |@");
while (true) {
String userPrompt = console.readLine(inputPrompt);
if (userPrompt == null || userPrompt.isBlank()
|| userPrompt.equalsIgnoreCase("exit")
|| userPrompt.equalsIgnoreCase("quit")) {
status("@|bold,yellow Shutting down the forge...|@");
logToFile("[SYSTEM] Shutting down.");
break;
}
logToFile("[USER] " + userPrompt);
processDemand(userPrompt);
}
}
// ==================== ORCHESTRATION ====================
/**
* Entry point for every user request — delegates to the
* Supervisor+WorkflowExecutor pipeline.
*/
private void processDemand(String userPrompt) throws Exception {
supervisorWorkflow(userPrompt);
}
/**
* Legacy Router loop — used as fallback when the Supervisor fails to produce a
* valid plan.
*/
private void processDemandRouter(String userPrompt) throws Exception {
LoopState state = new LoopState();
while (!state.taskResolved) {
if (++state.loopIterations > MAX_LOOP_ITERATIONS) {
status("@|bold,red [LOOP GUARD] Maximum orchestration iterations reached ("
+ MAX_LOOP_ITERATIONS + "). Aborting demand.|@");
logToFile("[SYSTEM] Loop guard triggered after " + MAX_LOOP_ITERATIONS + " iterations. Last error: "
+ truncate(state.lastError, 300));
break;
}
if (state.cacheList == null)
state.cacheList = listCachedTools().stream().reduce((a, b) -> a + ",\n" + b).orElse("Empty");
String statePrompt = buildStatePrompt(userPrompt, state, state.cacheList);
status(PRE_ROUTER + "Analyzing Intent and Metadata Schemas...|@");
String routerAction = router.invoke(statePrompt);
logToFile("[ROUTER ACTION] " + routerAction);
// Empty response means the LLM call failed (timeout, quota, network) — not a
// hallucination.
if (routerAction.isBlank()) {
status("@|bold,red [ROUTER] LLM returned empty response (timeout or quota). Aborting demand.|@");
logToFile("[ERROR] Router returned empty response — likely timeout or rate limit. Demand aborted.");
state.taskResolved = true;
continue;
}
int colon = routerAction.indexOf(':');
String command = (colon != -1 ? routerAction.substring(0, colon) : routerAction).trim();
switch (command) {
case "DELEGATE_CHAT" -> handleDelegateChat(userPrompt, state);
case "SEARCH" -> handleSearch(routerAction.substring(colon + 1).trim(), state);
case "EDIT" -> handleEdit(routerAction.substring(colon + 1).trim(), state);
case "CREATE" -> handleCreate(routerAction.substring(colon + 1).trim(), state);
case "EXECUTE" -> handleExecute(routerAction, colon, userPrompt, state);
default -> {
status("@|bold,red [ROUTER] Unexpected response format. Halting. Response: |@" + routerAction);
logToFile("[WARN] Unexpected router output (possible hallucination): " + routerAction);
state.taskResolved = true;
}
}
}
}
// ==================== PROMPT BUILDERS ====================
private String buildHistory() {
if (conversationMemory.isEmpty())
return "No previous context.";
// Iterate the Deque back-to-front accumulating entries that fit the budget,
// without copying to ArrayList — uses the native descending iterator of
// ArrayDeque.
var it = conversationMemory.descendingIterator();
int budget = MAX_HISTORY_CHARS;
var selected = new ArrayDeque<String>();
while (it.hasNext()) {
String entry = it.next();
int len = entry.length() + 1;
if (budget - len < 0)
break;
budget -= len;
selected.addFirst(entry); // restore original chronological order
}
return String.join("\n", selected);
}
private String buildSystemContext() {
return "[System Clock]\n" + buildClock() + "\n\n" + WORKSPACE_TOPOLOGY;
}
private String buildClock() {
return LocalDateTime.now().format(FMT_CLOCK)
+ " | Local System Zone: " + java.time.ZoneId.systemDefault();
}
private String buildStatePrompt(String userPrompt, LoopState state, String cacheList) {
String fallbackText = state.lastError == null ? "No previous errors."
: "A FAILURE OCCURRED IN THE LAST EXECUTION WITH THE FOLLOWING TRACE. REQUIRED FIX: " + state.lastError;
String historyList = buildHistory();
String ragSection = state.ragContext.isEmpty() ? "No recent searches." : state.ragContext;
return String.format("""
%s
[Recent Chat History]
%s
[System State]
Cached Tools (JSON format):
[%s]
[RAG Search Results]
%s
%s
Original User Request: %s
Decide next action: EXECUTE, CREATE, EDIT, SEARCH, or DELEGATE_CHAT.
""", buildSystemContext(), historyList, cacheList, ragSection, fallbackText, userPrompt);
}
// ==================== HANDLERS ====================
private void handleDelegateChat(String userPrompt, LoopState state) {
status("@|bold,yellow \uD83D\uDCAC [ASSISTANT] Generating intelligent response...|@");
String chatMessage = assistant
.invoke(buildAssistantPrompt(userPrompt, state.ragContext, state.cacheList));
// ── GUARDRAIL: if the assistant suggests a real cached tool, redirect to
// EXECUTE ──
java.util.regex.Matcher m = SAFE_TOOL_NAME.matcher(chatMessage);
while (m.find()) {
String candidate = m.group();
if (isToolNameSafe(candidate) && Files.exists(TOOLS_DIR.resolve(candidate))) {
// Only override if the context suggests intent: "use X.java", "run X.java", or
// if it's in a code block
int start = m.start();
String context = chatMessage.substring(Math.max(0, start - 20), start).toLowerCase();
boolean looksLikeIntent = context.contains("use") || context.contains("run")
|| context.contains("execute")
|| context.contains("tool") || context.contains("script") || context.contains("java");
if (looksLikeIntent) {
status("@|bold,yellow [GUARDRAIL] DELEGATE_CHAT suggested '" + candidate
+ "' \u2014 overriding to EXECUTE|@");
logToFile("[GUARDRAIL] DELEGATE_CHAT referenced cached tool '" + candidate
+ "'. Redirecting loop to EXECUTE.");
state.ragContext = "ROUTING CORRECTION: The previous routing decision was wrong. "
+ "Tool '" + candidate + "' is cached and MUST be executed directly. "
+ "Respond with EXECUTE: " + candidate + " <args from user prompt>. "
+ "Do NOT use DELEGATE_CHAT.\n\n" + state.ragContext;
addToMemory("USER: " + userPrompt);
return; // skip display and taskResolved — loop will re-route to EXECUTE
}
}
}
// ── END GUARDRAIL ──
resultBuffer.setLength(0);
resultBuffer.append(chatMessage.strip());
if (silent) {
System.out.println(chatMessage.strip());
} else {
System.out.println(AUTO.string("\n@|cyan " + chatMessage + "|@\n"));
}
logToFile("[CHAT RESULT]\n" + chatMessage);
addToMemory("USER: " + userPrompt);
addToMemory("SYSTEM (CHAT): " + (chatMessage.length() > 200
? chatMessage.substring(0, 200).replace("\n", " ") + "..."
: chatMessage.replace("\n", " ")));
state.taskResolved = true;
}
private void handleSearch(String query, LoopState state) {
if (++state.searchCount > MAX_SEARCH_PER_DEMAND) {
status("@|bold,red [SEARCH GUARD] Maximum searches per demand reached ("
+ MAX_SEARCH_PER_DEMAND + "). Aborting.|@");
logToFile("[SYSTEM] Search guard triggered after " + MAX_SEARCH_PER_DEMAND + " searches. Last query: "
+ query);
state.taskResolved = true;
return;
}
status("@|bold,cyan \uD83D\uDD0D [WEB SEARCH] Searching infrastructure: |@" + query);
String searchResult = searchWeb(query);
state.ragContext = "Query: " + query + "\nResults:\n" + searchResult;
addToMemory("SYSTEM (SEARCHED): " + query);
status("@|bold,yellow \uD83D\uDD04 Reloading Orchestrator with fresh contextual knowledge...|@");
boolean failed = searchResult.isBlank() || searchResult.startsWith("[searcher] LLM API call failed");
logToFile((failed ? "[SEARCH FAILED] " : "[SEARCH OK] ") + query + "\nOutcome: " + searchResult);
}
private void handleEdit(String editPayload, LoopState state) {
status(PRE_CODER + "Modifying existing tool -> |@" + editPayload);
int firstSpace = editPayload.indexOf(' ');
String targetTool = firstSpace == -1 ? editPayload : editPayload.substring(0, firstSpace).trim();
String changes = firstSpace == -1 ? "Fix or update according to user prompt"
: editPayload.substring(firstSpace).trim();
String existingCode;
try {
existingCode = Files.readString(TOOLS_DIR.resolve(targetTool));
} catch (Exception e) {
logToFile("[ERROR] Failed to read tool: " + targetTool + " — " + e.getMessage());
existingCode = "Tool code unreadable/missing.";
}
runCoderPipeline(coder.invoke(buildCoderEditPrompt(changes, existingCode, state.lastError)), state, false);
}
private void handleCreate(String instruction, LoopState state) {
status(PRE_CODER + "Tool missing (or corrupted). Developing new Tool -> |@" + instruction);
runCoderPipeline(coder.invoke(buildCoderCreatePrompt(instruction, state.lastError)), state, true);
}
private void runCoderPipeline(String generatedCode, LoopState state, boolean isCreate) {
if (generatedCode.isBlank()) {
state.lastError = "Coder LLM returned empty response (API error). Retrying.";
return;
}
try {
CodeGenResult gen = handleCodeGeneration(generatedCode);
state.lastError = null;
state.cacheList = null;
if (isCreate) {
handleTest(gen.fileName(), gen.metadataContent(), state);
}
runGarbageCollector();
} catch (IOException e) {
logToFile("[ERROR] handleCodeGeneration failed: " + e.getMessage());
state.lastError = "Code generation I/O failure: " + e.getMessage();
}
status("@|bold,yellow Returning control to [ROUTER] to invoke the produced tool...|@");
}
/**
* Runs a Tester-agent-generated invocation immediately after CREATE.
* On failure sets state.lastError + increments crashRetries for auto-heal via
* EDIT.
*/
private void handleTest(String fileName, String metadataContent, LoopState state) {
if (skipTest || state.crashRetries > 0)
return;
status(PRE_TESTER + "Generating test invocation for: |@" + fileName);
logToFile("[TESTER] Running auto-test for: " + fileName);
String toolSource;
try {
toolSource = Files.readString(TOOLS_DIR.resolve(fileName));
} catch (IOException e) {
logToFile("[TESTER] Could not read tool source — skipping test: " + e.getMessage());
return;
}
String testResponse = tester.invoke(
"Tool file: " + fileName + "\n\nMetadata:\n" + metadataContent + "\n\nSource code:\n" + toolSource);
if (testResponse.isBlank() || !testResponse.contains("TEST_INVOCATION:")) {
logToFile("[TESTER] Invalid response from tester agent — skipping test.");
return;
}
String invocation = testResponse.substring(testResponse.indexOf("TEST_INVOCATION:") + 16).trim();
List<String> parts = tokenizeArgs(invocation);
if (parts.isEmpty() || parts.get(0).isBlank()) {
logToFile("[TESTER] Empty invocation after parsing — skipping test.");
return;
}
String testToolName = parts.get(0);
if (!isToolNameSafe(testToolName)) {
logToFile("[TESTER] Unsafe tool name from tester agent '" + testToolName + "' — skipping test.");
return;
}
List<String> testArgs = parts.subList(1, parts.size());
ProcessResult testResult;
try {
testResult = executeToolProcess(testToolName, testArgs);
} catch (Exception e) {
logToFile("[TESTER] Test execution threw exception: " + e.getMessage());
state.lastError = "[AUTO-TEST EXCEPTION] " + e.getMessage();
state.crashRetries++;
return;
}
logToFile("[TESTER] Test result:\n" + testResult.output());
if (testResult.success()) {
status("@|bold,green [TEST PASSED] Tool validated successfully.|@");
logToFile("[TESTER] Test PASSED for: " + fileName);
} else {
status("@|bold,red [TEST FAILED] Tool failed validation. Routing for auto-heal...|@");