-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAceClawDaemon.java
More file actions
3046 lines (2869 loc) · 149 KB
/
Copy pathAceClawDaemon.java
File metadata and controls
3046 lines (2869 loc) · 149 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
package dev.aceclaw.daemon;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import dev.aceclaw.core.agent.*;
import dev.aceclaw.core.util.WaitSupport;
import dev.aceclaw.core.llm.LlmClient;
import dev.aceclaw.daemon.cron.CronScheduler;
import dev.aceclaw.daemon.cron.CronExpression;
import dev.aceclaw.daemon.cron.CronJob;
import dev.aceclaw.daemon.cron.JobStore;
import dev.aceclaw.daemon.cron.CronTool;
import dev.aceclaw.daemon.deferred.DeferCheckTool;
import dev.aceclaw.daemon.deferred.DeferredActionScheduler;
import dev.aceclaw.daemon.deferred.DeferredActionStore;
import dev.aceclaw.daemon.deferred.DeferredEventFeed;
import dev.aceclaw.daemon.heartbeat.HeartbeatRunner;
import dev.aceclaw.infra.event.DeferEvent;
import dev.aceclaw.infra.event.EventBus;
import dev.aceclaw.infra.event.SchedulerEvent;
import dev.aceclaw.infra.health.*;
import dev.aceclaw.llm.LlmClientFactory;
import dev.aceclaw.memory.AutoMemoryStore;
import dev.aceclaw.memory.CandidateStateMachine;
import dev.aceclaw.memory.CandidateStore;
import dev.aceclaw.memory.CrossSessionPatternMiner;
import dev.aceclaw.memory.DailyJournal;
import dev.aceclaw.memory.HistoricalLogIndex;
import dev.aceclaw.memory.HistoricalSessionSnapshot;
import dev.aceclaw.memory.MarkdownMemoryStore;
import dev.aceclaw.memory.CorrectionRulePromoter;
import dev.aceclaw.memory.MemoryConsolidator;
import dev.aceclaw.memory.StrategyRefiner;
import dev.aceclaw.memory.TrendDetector;
import dev.aceclaw.memory.WorkspacePaths;
import dev.aceclaw.security.Capability;
import dev.aceclaw.security.CapabilityAware;
import dev.aceclaw.security.DefaultPermissionPolicy;
import dev.aceclaw.security.PermissionManager;
import dev.aceclaw.security.audit.CapabilityAuditLog;
import dev.aceclaw.mcp.McpClientManager;
import dev.aceclaw.mcp.McpServerConfig;
import dev.aceclaw.tools.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.time.Instant;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* The AceClaw daemon — a persistent system process that orchestrates all services.
*
* <p>Boot sequence: Config -> Lock -> Infra -> Sessions -> Router -> Agent -> Listener -> Ready
*
* <p>The daemon manages:
* <ul>
* <li>Configuration loading (AceClawConfig)</li>
* <li>Instance locking (DaemonLock)</li>
* <li>Unix Domain Socket listener (UdsListener)</li>
* <li>Session management (SessionManager)</li>
* <li>Request routing (RequestRouter)</li>
* <li>Streaming agent handler with permission management</li>
* <li>Graceful shutdown (ShutdownManager)</li>
* </ul>
*/
public final class AceClawDaemon {
private static final String HUMAN_REVIEW_APPLIED_ACTION = "human_review_applied";
private static final int REVIEW_COUNT_WINDOW = 200;
private static final Logger log = LoggerFactory.getLogger(AceClawDaemon.class);
private final Path homeDir;
private final AceClawConfig config;
private final ObjectMapper objectMapper;
private final DaemonLock lock;
private final ShutdownManager shutdownManager;
private final SessionManager sessionManager;
private final SessionHistoryStore historyStore;
private final AutoMemoryStore memoryStore;
private final HistoricalLogIndex historicalLogIndex;
private final LearningExplanationStore learningExplanationStore;
private final LearningExplanationRecorder learningExplanationRecorder;
private final LearningValidationStore learningValidationStore;
private final LearningValidationRecorder learningValidationRecorder;
private final LearningSignalReviewStore learningSignalReviewStore;
private final LearningMaintenanceRunStore learningMaintenanceRunStore;
private final LearningMaintenanceRecoveryStore learningMaintenanceRecoveryStore;
private final MarkdownMemoryStore markdownStore;
private final JobStore cronJobStore;
private final EventBus eventBus;
private final SchedulerEventFeed schedulerEventFeed;
private final DeferredEventFeed deferredEventFeed;
private final SkillDraftEventFeed skillDraftEventFeed;
private final HealthMonitor healthMonitor;
private final RequestRouter router;
private final ConnectionBridge connectionBridge;
private final UdsListener udsListener;
private final Instant startedAt;
// Set during wireAgentHandler(), used for boot execution and cron scheduler
private LlmClient bootLlmClient;
private ToolRegistry bootToolRegistry;
private String bootModel;
private String bootSystemPrompt;
private CronScheduler cronScheduler;
private LearningMaintenanceScheduler learningMaintenanceScheduler;
private DeferredActionScheduler deferredActionScheduler;
private DeferredActionStore deferredActionStore;
private DeferCheckTool deferCheckTool;
/** Browser dashboard bridge (issue #431); null when {@code webSocket.enabled=false}. */
/**
* Volatile because {@link #forwardSchedulerEventToWs} reads this on
* eventBus subscriber threads and the field is written once in
* {@link #start()}. Without volatile the JMM only guarantees visibility
* via the eventBus queue's internal synchronization — true in practice
* but fragile to refactor. The volatile read is essentially free and
* documents the cross-thread access.
*/
private volatile WebSocketBridge webSocketBridge;
private volatile boolean running;
private AceClawDaemon(Path homeDir) {
this(homeDir, null);
}
private AceClawDaemon(Path homeDir, String providerOverride) {
this.homeDir = homeDir;
this.startedAt = Instant.now();
// Load configuration (files + env vars)
Path workingDir = Path.of(System.getProperty("user.dir"));
this.config = AceClawConfig.load(workingDir, providerOverride);
// Infrastructure
this.objectMapper = createObjectMapper();
this.shutdownManager = new ShutdownManager();
// Event bus (async pub/sub for health events, agent events, etc.)
this.eventBus = new EventBus();
eventBus.start();
this.schedulerEventFeed = new SchedulerEventFeed();
eventBus.subscribe(SchedulerEvent.class, schedulerEventFeed::append);
// #459: also forward scheduler events to the dashboard via the WS
// bridge (when one is configured). Lazy-reads webSocketBridge at
// fire time because the bridge is constructed later in start().
// The null-check is pure defense in depth — the cron scheduler
// itself isn't started until after the bridge is up (see start()),
// so in practice no SchedulerEvent can fire while bridge is null.
eventBus.subscribe(SchedulerEvent.class, this::forwardSchedulerEventToWs);
this.deferredEventFeed = new DeferredEventFeed();
eventBus.subscribe(DeferEvent.class, deferredEventFeed::append);
this.skillDraftEventFeed = new SkillDraftEventFeed();
// Health monitor (aggregates per-component health checks)
this.healthMonitor = new HealthMonitor(eventBus);
// Lock
this.lock = new DaemonLock(homeDir.resolve("aceclaw.pid"));
// Sessions & history persistence
this.sessionManager = new SessionManager();
this.historyStore = new SessionHistoryStore(homeDir);
// Auto-memory store (workspace-scoped with daily journal)
AutoMemoryStore ms = null;
try {
ms = AutoMemoryStore.forWorkspace(homeDir, workingDir);
} catch (java.io.IOException e) {
log.warn("Failed to initialize auto-memory store: {}", e.getMessage());
}
this.memoryStore = ms;
HistoricalLogIndex hli = null;
try {
hli = new HistoricalLogIndex(homeDir);
} catch (java.io.IOException e) {
log.warn("Failed to initialize historical log index: {}", e.getMessage());
}
this.historicalLogIndex = hli;
this.learningExplanationStore = new LearningExplanationStore();
this.learningExplanationRecorder = new LearningExplanationRecorder(learningExplanationStore);
this.learningValidationStore = new LearningValidationStore();
this.learningValidationRecorder = new LearningValidationRecorder(learningValidationStore);
this.learningSignalReviewStore = new LearningSignalReviewStore();
this.learningMaintenanceRunStore = new LearningMaintenanceRunStore();
this.learningMaintenanceRecoveryStore = new LearningMaintenanceRecoveryStore();
// Markdown memory store (persistent MEMORY.md + topic files)
MarkdownMemoryStore mds = null;
try {
mds = MarkdownMemoryStore.forWorkspace(homeDir, workingDir);
} catch (java.io.IOException e) {
log.warn("Failed to initialize markdown memory store: {}", e.getMessage());
}
this.markdownStore = mds;
this.cronJobStore = new JobStore(homeDir);
try {
this.cronJobStore.load();
} catch (java.io.IOException e) {
log.warn("Failed to preload cron job store: {}", e.getMessage());
}
this.router = new RequestRouter(sessionManager, objectMapper);
this.connectionBridge = new ConnectionBridge(router, objectMapper);
// Wire the streaming agent handler with LLM, tools, and permissions
wireAgentHandler(workingDir);
// UDS listener
this.udsListener = new UdsListener(
homeDir.resolve("aceclaw.sock"),
connectionBridge
);
}
/**
* Wires the streaming agent handler into the request router.
*
* <p>Creates the LLM client (from config), tool registry (with all tools),
* permission manager, and streaming agent loop.
*/
private void wireAgentHandler(Path workingDir) {
// 1. LLM client (provider-agnostic via factory)
String apiKey = config.apiKey();
if (apiKey == null || apiKey.isBlank()) {
log.warn("API key not configured; set ANTHROPIC_API_KEY (or OPENAI_API_KEY for non-Anthropic providers) or add apiKey to ~/.aceclaw/config.json");
apiKey = "not-configured";
}
String model = config.resolvedModel();
LlmClient rawLlmClient;
if ("anthropic".equals(config.provider())) {
// Only allow Keychain fallback when the credentials actually came
// from Claude CLI's shared store. Profile-supplied apiKeys stay
// isolated from that store to prevent cross-account contamination.
rawLlmClient = LlmClientFactory.createAnthropicClient(
apiKey, config.refreshToken(), config.baseUrl(),
config.context1m(), config.extraAnthropicBetas(),
config.credentialsFromKeychain());
if (rawLlmClient instanceof dev.aceclaw.llm.anthropic.AnthropicClient ac) {
// Tell the client which model is configured so capabilities() can detect 4.6 → 1M
ac.setConfiguredModel(model);
// In isolated mode (profile-supplied credentials), persist refreshed tokens
// back to the profile in config.json so they survive a daemon restart.
String profileName = config.activeProfileName();
if (!config.credentialsFromKeychain() && profileName != null) {
ac.setTokenPersistCallback(update ->
AceClawConfig.persistProfileCredentials(
profileName, update.accessToken(), update.refreshToken()));
}
}
} else {
rawLlmClient = LlmClientFactory.create(
config.provider(), apiKey, config.refreshToken(), config.baseUrl(), model);
}
// Wrap LLM client with circuit breaker for fault isolation
var cbConfig = CircuitBreakerConfig.defaultForLlm();
var circuitBreaker = new CircuitBreaker(cbConfig, eventBus);
LlmClient llmClient = new CircuitBreakerLlmClient(rawLlmClient, circuitBreaker);
// Register circuit breaker health check
healthMonitor.register(new CircuitBreakerHealthCheck(circuitBreaker));
log.info("LLM circuit breaker enabled: threshold={}, timeout={}s",
cbConfig.failureThreshold(), cbConfig.resetTimeout().toSeconds());
// Resolve effective context window: explicit config > provider default
int contextWindow = config.contextWindowTokens() > 0
? config.contextWindowTokens()
: llmClient.capabilities().contextWindowTokens();
String contextSource = config.contextWindowTokens() > 0 ? "from config" : "auto-detected";
log.info("Context window: {}K ({})", contextWindow / 1000, contextSource);
// 2. Tool registry (with shared read-tracking for read-before-write enforcement)
var toolRegistry = new ToolRegistry();
var writeFileTool = new WriteFileTool(workingDir);
toolRegistry.register(new ReadFileTool(workingDir, writeFileTool.readFiles()));
toolRegistry.register(writeFileTool);
toolRegistry.register(new EditFileTool(workingDir));
toolRegistry.register(new BashExecTool(workingDir));
toolRegistry.register(new GlobSearchTool(workingDir));
toolRegistry.register(new GrepSearchTool(workingDir));
toolRegistry.register(new ListDirTool(workingDir));
toolRegistry.register(new WebFetchTool(workingDir));
toolRegistry.register(new CronTool(
cronJobStore, () -> cronScheduler != null && cronScheduler.isRunning()));
// Deferred action store and tool (registered now, scheduler wired later after handler creation)
this.deferredActionStore = new DeferredActionStore(homeDir);
try {
this.deferredActionStore.load();
} catch (java.io.IOException e) {
log.warn("Failed to preload deferred action store: {}", e.getMessage());
}
// DeferCheckTool registered with null scheduler; scheduler wired after handler creation
this.deferCheckTool = new DeferCheckTool(null);
toolRegistry.register(deferCheckTool);
// Memory management tool (agent can actively save/search/list memories)
if (memoryStore != null) {
toolRegistry.register(new dev.aceclaw.tools.MemoryTool(memoryStore, workingDir));
}
// Browser tool (lazy Chromium instance, registered as shutdown participant)
var browserTool = new BrowserTool(workingDir);
toolRegistry.register(browserTool);
shutdownManager.register(new ShutdownManager.ShutdownParticipant() {
@Override public String name() { return "Browser"; }
@Override public int priority() { return 80; }
@Override public void onShutdown() { browserTool.close(); }
});
// Platform-conditional tools (macOS only)
if (AppleScriptTool.isSupported()) {
toolRegistry.register(new AppleScriptTool(workingDir));
toolRegistry.register(new ScreenCaptureTool(workingDir));
}
// Web search (Brave when API key set, DuckDuckGo Lite fallback otherwise)
if (config.braveSearchApiKey() != null) {
toolRegistry.register(new WebSearchTool(workingDir, config.braveSearchApiKey()));
} else {
toolRegistry.register(new WebSearchTool(workingDir));
}
// MCP servers (config-driven external tool providers)
// Started asynchronously to avoid blocking daemon boot (npx downloads can be slow).
// Tools are registered incrementally as each server connects, so one slow/failing server
// does not block tools from already-succeeded servers.
// The mcpInitFuture completes once the first server's tools are available (or all fail).
var mcpConfig = McpServerConfig.load(workingDir);
var mcpInitFuture = new java.util.concurrent.CompletableFuture<Void>();
final McpClientManager mcpManager;
if (!mcpConfig.isEmpty()) {
mcpManager = new McpClientManager(mcpConfig);
shutdownManager.register(new ShutdownManager.ShutdownParticipant() {
@Override public String name() { return "MCP Servers"; }
@Override public int priority() { return 85; }
@Override public void onShutdown() { mcpManager.close(); }
});
mcpManager.setOnToolRemoved(toolName -> {
toolRegistry.unregister(toolName);
log.info("MCP: unregistered stale tool '{}'", toolName);
});
log.info("MCP: {} server(s) configured, initializing in background...", mcpConfig.size());
Thread.ofVirtual().name("mcp-init").start(() -> {
try {
mcpManager.start(tools -> {
// Register each server's tools as soon as they are discovered
for (var tool : tools) {
toolRegistry.register(tool);
}
log.info("MCP: registered {} tool(s) incrementally", tools.size());
// Complete the future on the first successful server so requests
// don't wait for slow/failing servers
mcpInitFuture.complete(null);
});
// If no server succeeded, the future is still pending — complete it now
mcpInitFuture.complete(null);
} catch (Exception e) {
log.error("MCP initialization failed: {}", e.getMessage(), e);
mcpInitFuture.complete(null);
}
});
} else {
mcpManager = null;
mcpInitFuture.complete(null);
}
log.info("Registered {} base tools", toolRegistry.size());
// 3. Permission manager — mode from config (default: "normal")
// Created early because sub-agent permission checker references it.
// Audit dir is resolved against the daemon's configured homeDir
// (NOT user.home) so AceClawDaemon.create(Path) overrides and
// test isolations write audit artifacts under the same root as
// every other persisted thing (pid, sock, transcripts,
// checkpoints, ...).
var permissionManager = new PermissionManager(
new DefaultPermissionPolicy(config.permissionMode()),
buildCapabilityAuditLog(homeDir.resolve("audit")));
// 4. Sub-agent infrastructure (task delegation) and skills
var agentTypeRegistry = AgentTypeRegistry.load(workingDir);
// Sub-agent permission checker: auto-approve READ tools + session-approved, deny rest
// Note: "memory" excluded — MemoryTool has save/delete (write operations).
// "skill" included — skill execution is gated by skill config's allowedTools.
var builtinReadOnlyTools = java.util.Set.of(
"read_file", "glob", "grep", "list_directory",
"web_fetch", "web_search", "screen_capture", "skill");
// Merge built-in whitelist with extra tools from config
var extraTools = config.subAgentAutoApproveTools();
java.util.Set<String> readOnlyTools;
if (extraTools.isEmpty()) {
readOnlyTools = builtinReadOnlyTools;
} else {
readOnlyTools = new java.util.HashSet<>(builtinReadOnlyTools);
readOnlyTools.addAll(extraTools);
readOnlyTools = java.util.Set.copyOf(readOnlyTools);
log.info("Sub-agent auto-approve tools extended with: {}", extraTools);
}
// Structural-denial probe: routes the sub-agent's intended tool call
// through the policy's evaluateStructural before any allow-list
// shortcut, so a prior "always allow write_file" approval cannot
// route a sub-agent past the .env / .ssh / /etc/ hard-denial layer
// (Codex P1 on #495).
//
// Audit attribution: the denial is recorded via
// permissionManager.checkStructural which writes a v2 audit entry
// tagged with the originating session's Provenance and the tool
// name as the allowlistKey. Without that audit, a sub-agent's
// attempt to write .env would be invisible to forensics — the
// dispatcher main path's audit hook is bypassed here.
var subAgentToolRegistry = toolRegistry;
var subAgentMapper = objectMapper;
SubAgentStructuralCheck structuralCheck = (toolName, inputJson, sessionId) -> {
var toolOpt = subAgentToolRegistry.get(toolName);
if (toolOpt.isEmpty()) return null;
if (!(toolOpt.get() instanceof CapabilityAware aware)) return null;
Capability cap;
try {
var argsNode = (inputJson == null || inputJson.isBlank())
? subAgentMapper.createObjectNode()
: subAgentMapper.readTree(inputJson);
cap = aware.toCapability(argsNode);
} catch (Exception malformed) {
// Unparseable args — fall through to the normal allow-list
// logic rather than crash the dispatcher. The standard
// sub-agent gate will still deny non-read-only tools that
// lack session approval.
return null;
}
if (cap == null) return null;
var provenance = dev.aceclaw.security.Provenance.fromNullableSessionId(sessionId);
var denial = permissionManager.checkStructural(cap, provenance, toolName);
return denial == null ? null : denial.reason();
};
// Sub-agent allow-list lookup is now per-session (#457): the
// checker receives the calling agent's sessionId on every check
// and looks up the allow-list keyed on that session. This closes
// the leak where a sub-agent in session B silently inherited an
// approval the user granted in session A — a regression of #456
// confined to the sub-agent path until threading was done.
var subAgentPermChecker = new SubAgentPermissionChecker(
readOnlyTools, permissionManager::hasSessionApproval, structuralCheck);
// Project rules for sub-agent system prompts
String projectRules = SystemPromptLoader.extractProjectRules(workingDir);
var subAgentRunner = new SubAgentRunner(
llmClient, toolRegistry, model, workingDir,
config.maxTokens(), config.thinkingBudget(),
subAgentPermChecker, projectRules);
// Transcript store for sub-agent debugging/auditing
var transcriptStore = new TranscriptStore(homeDir.resolve("transcripts"));
subAgentRunner.setTranscriptStore(transcriptStore, "default");
transcriptStore.cleanup(); // Clean up old transcripts on startup
toolRegistry.register(new dev.aceclaw.tools.TaskTool(subAgentRunner, agentTypeRegistry));
toolRegistry.register(new dev.aceclaw.tools.TaskOutputTool(subAgentRunner));
log.info("Sub-agent types available: {}", agentTypeRegistry.names());
// Skill system (project + user skills from .aceclaw/skills/)
var skillRegistry = SkillRegistry.load(workingDir);
DynamicSkillGenerator dynamicSkillGenerator = null;
{
var contentResolver = new SkillContentResolver(workingDir);
var skillTool = new SkillTool(skillRegistry, contentResolver, subAgentRunner);
toolRegistry.register(skillTool);
if (!skillRegistry.isEmpty()) {
log.info("Skills registered: {}", skillRegistry.names());
} else {
log.debug("No disk-backed skills found, SkillTool registered for runtime skills only");
}
}
// 5. System prompt (with 8-tier memory hierarchy + daily journal + model identity + budget)
// Budget scales with context window: small models (32K) get smaller memory budgets
DailyJournal journal = memoryStore != null ? memoryStore.getDailyJournal() : null;
var promptBudget = SystemPromptBudget.forContextWindow(
contextWindow, config.maxTokens());
log.info("System prompt budget: {}K per tier, {}K total (context={}K, maxOutput={}K)",
promptBudget.maxPerTierChars() / 1000, promptBudget.maxTotalChars() / 1000,
contextWindow / 1000, config.maxTokens() / 1000);
// Collect registered tool names for dynamic tool guidance in system prompt
var toolNames = toolRegistry.all().stream()
.map(dev.aceclaw.core.agent.Tool::name)
.collect(java.util.stream.Collectors.toSet());
String systemPrompt = SystemPromptLoader.load(
workingDir, memoryStore, journal, markdownStore, model, config.provider(), promptBudget,
toolNames, config.braveSearchApiKey() != null);
// 5b. Inject skill descriptions into system prompt so the LLM knows
// what each skill does and when to invoke it proactively.
String skillDescriptions = skillRegistry.isEmpty() ? "" : skillRegistry.formatDescriptions();
if (!skillDescriptions.isEmpty()) {
systemPrompt = systemPrompt + "\n\n" + skillDescriptions;
}
// 6. Context compaction (accounting for actual system prompt size)
int systemPromptTokens = dev.aceclaw.core.agent.ContextEstimator.estimateTokens(systemPrompt);
var compactionConfig = new CompactionConfig(
contextWindow, config.maxTokens(), systemPromptTokens,
0.85, 0.60, 5);
var compactor = new MessageCompactor(llmClient, model, compactionConfig);
log.info("System prompt: {} chars (~{} tokens), effective conversation window: {} tokens",
systemPrompt.length(), systemPromptTokens, compactionConfig.effectiveWindowTokens());
// 7. Streaming agent loop (with compaction support + context budget)
var loopConfig = dev.aceclaw.core.agent.AgentLoopConfig.builder()
.maxIterations(config.maxTurns())
.build();
var agentLoop = new StreamingAgentLoop(
llmClient, toolRegistry, model, systemPrompt,
config.maxTokens(), config.thinkingBudget(),
contextWindow, compactor, loopConfig);
// Log startup token budget breakdown
int toolDefTokens = ContextEstimator.estimateToolDefinitions(toolRegistry.toDefinitions());
int availableTokens = contextWindow - config.maxTokens();
log.info("Context budget: system={}t, tools={}t, total_fixed={}t, available={}t (window={}t, output={}t)",
systemPromptTokens, toolDefTokens,
systemPromptTokens + toolDefTokens, availableTokens,
contextWindow, config.maxTokens());
// 8. Streaming agent handler
var agentHandler = new StreamingAgentHandler(
sessionManager, agentLoop, toolRegistry, permissionManager, objectMapper);
// 8a. WebSocket bridge for browser dashboard (issue #431). Disabled by default.
// Constructed but NOT started here; lifecycle binds to udsListener below so the
// port is held only while the daemon is accepting clients.
if (config.webSocketEnabled()) {
this.webSocketBridge = new WebSocketBridge(
config.webSocketHost(), config.webSocketPort(), objectMapper,
config.webSocketAllowedOrigins());
agentHandler.setWebSocketBridge(this.webSocketBridge);
// Issue #445: respond to sessions.list requests from the dashboard
// sidebar. The reply is a one-shot point-to-point message rather
// than a broadcast envelope — semantically a request-response,
// not a stream event, so we ctx.send the JSON directly to the
// requesting client and skip the EventMultiplexer fan-out path.
final var sessionsRef = sessionManager;
final var mapperRef = objectMapper;
final var bridgeRef = this.webSocketBridge;
this.webSocketBridge.setInboundHandler((ctx, message) -> {
var methodNode = message.get("method");
if (methodNode == null) return;
var method = methodNode.asText("");
switch (method) {
case "sessions.list" -> handleSessionsList(ctx, mapperRef, sessionsRef, agentHandler);
case "snapshot.request" -> handleSnapshotRequest(ctx, message, mapperRef, bridgeRef);
// #459 layer 2: dashboard sidebar fetches the current
// cron-job snapshot on connect. Reply is point-to-point
// (not broadcast), same one-shot pattern as sessions.list.
// Field reads of cronJobStore/cronScheduler are lazy via
// `this` so a dashboard that connects before cron has
// started just sees an empty job list.
case "scheduler.cron.status" ->
handleSchedulerCronStatus(ctx, mapperRef, cronJobStore, cronScheduler);
// Browser approve/deny → route to the same per-context
// CompletableFuture the CLI socket monitor would (issue
// #433). First response wins; the loser is logged and
// dropped. Per-context map cleanup is handled inside
// routePermissionResponse via the daemon-wide registry.
case "permission.response" -> agentHandler.routePermissionResponse(message);
default -> { /* unknown method: drop */ }
}
});
log.info("WebSocket bridge configured: {}:{} (allowed browser origins: {})",
config.webSocketHost(), config.webSocketPort(),
config.webSocketAllowedOrigins().isEmpty()
? "(none — browsers blocked)"
: config.webSocketAllowedOrigins());
}
// health.status reports dashboard reachability so the `aceclaw dashboard`
// CLI subcommand (#446) can discover the URL without hard-coding 3141.
// Initial state is "not yet running" — the real URL is published below
// by {@link #publishDashboardInfo} only AFTER the bridge has actually
// bound its port. If the user disabled WS in config, or Jetty fails to
// bind (port conflict with Jupyter / Docker / another local service),
// {@code enabled} stays false and the CLI prints a precise error
// instead of luring the user into opening someone else's service.
boolean dashboardBundled = WebSocketBridge.dashboardBundled();
router.setDashboardInfo(new RequestRouter.DashboardInfo(
false, "", dashboardBundled));
// Use config model for anthropic (user's choice), client's resolved model for other providers
// (factory may translate or fall back, e.g. copilot ignores anthropic model names)
String effectiveModel = "anthropic".equals(config.provider()) ? model : llmClient.defaultModel();
agentHandler.setLlmConfig(llmClient, effectiveModel, systemPrompt);
agentHandler.setTokenConfig(config.maxTokens(), config.thinkingBudget(), config.maxTurns(), contextWindow);
agentHandler.setContextAssemblyConfig(
markdownStore,
config.provider(),
promptBudget,
config.braveSearchApiKey() != null,
skillRegistry::formatDescriptions);
agentHandler.setMcpInitFuture(mcpInitFuture);
agentHandler.setRetryConfig(config.retryConfig());
agentHandler.setAdaptiveContinuationConfig(
config.adaptiveContinuationEnabled(),
config.adaptiveContinuationMaxSegments(),
config.adaptiveContinuationNoProgressThreshold(),
config.adaptiveContinuationMaxTotalTokens(),
config.adaptiveContinuationMaxWallClockSeconds());
agentHandler.setPlannerConfig(config.plannerEnabled(), config.plannerThreshold());
agentHandler.setAdaptiveReplanEnabled(config.adaptiveReplanEnabled());
agentHandler.setWatchdogConfig(
config.maxAgentTurns(), config.maxAgentWallTimeSec(),
config.maxAgentHardTurns(), config.maxAgentHardWallTimeSec());
agentHandler.setPlanBudgetConfig(
config.maxPlanStepWallTimeSec(),
config.maxPlanTotalWallTimeSec());
// Plan checkpoint store for crash-safe plan progress persistence and resume
var planCheckpointStore = new FilePlanCheckpointStore(
homeDir.resolve("checkpoints").resolve("plans"), objectMapper);
planCheckpointStore.cleanup(7); // clean old checkpoints on startup
agentHandler.setPlanCheckpointStore(planCheckpointStore);
agentHandler.setCompactor(compactor);
agentHandler.setMemoryStore(memoryStore, workingDir);
agentHandler.setAntiPatternGateFeedbackStore(new AntiPatternGateFeedbackStore(
workingDir,
config.antiPatternGateMinBlockedBeforeRollback(),
config.antiPatternGateMaxFalsePositiveRate()));
if (journal != null) {
agentHandler.setDailyJournal(journal);
}
// 9. Hook system (command hooks at tool lifecycle points)
var hookRegistry = HookRegistry.load(config.hooks());
if (!hookRegistry.isEmpty()) {
var hookExecutor = new CommandHookExecutor(hookRegistry, objectMapper, workingDir);
agentHandler.setHookExecutor(hookExecutor);
log.info("Hook system wired: {} matchers across {} event types",
hookRegistry.size(),
(hookRegistry.hasHooksFor("PreToolUse") ? 1 : 0) +
(hookRegistry.hasHooksFor("PostToolUse") ? 1 : 0) +
(hookRegistry.hasHooksFor("PostToolUseFailure") ? 1 : 0));
}
// 10. Self-improvement engine (post-turn learning analysis + strategy refinement + candidate pipeline)
// Shared lock serializing all draft generation, validation, and release operations.
// Prevents races between per-turn trigger, startup catch-up, and RPC handlers.
final var draftPipelineLock = new java.util.concurrent.locks.ReentrantLock();
CandidateStore candidateStoreRef = null;
ValidationGateEngine validationGateEngine = null;
AutoReleaseController autoReleaseController = null;
if (memoryStore != null) {
var errorDetector = new ErrorDetector(memoryStore);
var patternDetector = new PatternDetector(memoryStore);
var failureSignalDetector = new FailureSignalDetector();
var strategyRefiner = new StrategyRefiner(memoryStore);
if (config.skillDraftValidationEnabled()) {
validationGateEngine = new ValidationGateEngine(
config.skillDraftValidationStrictMode(),
config.skillDraftValidationReplayRequired(),
Path.of(config.skillDraftValidationReplayReport()),
config.skillDraftValidationMaxTokenEstimationErrorRatio());
}
// Candidate store for learning pipeline (promotion/demotion state machine)
CandidateStore cs = null;
if (config.candidatePromotionEnabled() || config.candidateInjectionEnabled()) {
try {
var smConfig = new CandidateStateMachine.Config(
config.candidatePromotionMinEvidence(),
config.candidatePromotionMinScore(),
config.candidatePromotionMaxFailureRate(),
3, java.util.Set.of());
cs = new CandidateStore(homeDir, smConfig);
cs.load();
log.info("Candidate store loaded: {} candidates", cs.all().size());
} catch (java.io.IOException e) {
log.warn("Failed to initialize candidate store: {}", e.getMessage());
cs = null;
}
}
final var validationGateForAuto = validationGateEngine;
final var candidateStoreForAuto = cs;
if (validationGateForAuto != null && cs != null && config.skillAutoReleaseEnabled()) {
autoReleaseController = new AutoReleaseController(
new AutoReleaseController.Config(
config.skillAutoReleaseMinCandidateScore(),
config.skillAutoReleaseMinEvidence(),
config.skillAutoReleaseCanaryMinAttempts(),
config.skillAutoReleaseCanaryMaxFailureRate(),
config.skillAutoReleaseCanaryMaxTimeoutRate(),
config.skillAutoReleaseCanaryMaxPermissionBlockRate(),
config.skillAutoReleaseRollbackMaxFailureRate(),
config.skillAutoReleaseRollbackMaxTimeoutRate(),
config.skillAutoReleaseRollbackMaxPermissionBlockRate(),
Duration.ofHours(Math.max(1, config.skillAutoReleaseHealthLookbackHours())),
config.skillAutoReleaseCanaryDwellHours()
),
validationGateForAuto
);
}
final var autoReleaseForAuto = autoReleaseController;
var selfImprovementEngine = new SelfImprovementEngine(
errorDetector, patternDetector, failureSignalDetector, memoryStore, strategyRefiner, cs,
config.candidatePromotionEnabled(),
(validationGateForAuto != null || candidateStoreForAuto != null) ? projectPath -> {
draftPipelineLock.lock();
try {
// Auto-generate skill drafts from newly promoted candidates
if (candidateStoreForAuto != null) {
var generator = new SkillDraftGenerator();
var summary = generator.generateFromPromoted(candidateStoreForAuto, projectPath);
publishSkillDraftCreatedEvents(summary, projectPath, "auto-promotion");
if (summary.createdDrafts() > 0) {
log.info("Auto skill draft generation: {} created, {} skipped",
summary.createdDrafts(), summary.skippedDrafts());
}
}
// Validate drafts and evaluate for auto-release
if (validationGateForAuto != null) {
var validation = validationGateForAuto.validateAll(projectPath, "auto-promotion");
publishSkillDraftValidationEvents(validation, workingDir, "auto-promotion");
if (autoReleaseForAuto != null && candidateStoreForAuto != null) {
var release = autoReleaseForAuto.evaluateAll(projectPath, candidateStoreForAuto, "auto-promotion");
publishSkillDraftReleaseEvents(release, workingDir, "auto-promotion");
}
}
} catch (Exception e) {
log.warn("Auto draft generation/validation failed: {}", e.getMessage());
} finally {
draftPipelineLock.unlock();
}
} : null);
selfImprovementEngine.setLearningExplanationRecorder(learningExplanationRecorder);
agentHandler.setSelfImprovementEngine(selfImprovementEngine);
candidateStoreRef = cs;
// Pass candidate store to agent handler for prompt injection
if (cs != null && config.candidateInjectionEnabled()) {
agentHandler.setCandidateStore(cs);
agentHandler.setCandidateInjectionEnabled(true);
agentHandler.setCandidateInjectionConfig(
config.candidateInjectionMaxCount(), config.candidateInjectionMaxTokens());
} else {
agentHandler.setCandidateInjectionEnabled(false);
}
// Wire runtime metrics exporter and injection audit log
var runtimeMetricsExporter = new RuntimeMetricsExporter();
agentHandler.setRuntimeMetricsExporter(runtimeMetricsExporter);
if (cs != null) {
// Resolve from homeDir (NOT user.home) so AceClawDaemon.create(Path)
// overrides and test isolations write the injection audit log under
// the same root as every other persisted thing. Same fix shape as
// the capability audit dir at the top of wireAgentHandler (#475).
agentHandler.setInjectionAuditLog(
new dev.aceclaw.memory.InjectionAuditLog(homeDir.resolve("memory")));
}
log.info("Self-improvement engine wired (with strategy refinement + candidate pipeline + runtime metrics)");
// Catch-up: generate drafts for any PROMOTED candidates that don't have drafts yet.
// This handles candidates promoted before the auto-trigger existed (pre-#175).
final var catchupCs = cs;
final var catchupValidation = validationGateEngine;
final var catchupAutoRelease = autoReleaseController;
if (catchupCs != null && !catchupCs.byState(dev.aceclaw.memory.CandidateState.PROMOTED).isEmpty()) {
Thread.ofVirtual().name("draft-catchup").start(() -> {
draftPipelineLock.lock();
try {
var generator = new SkillDraftGenerator();
var summary = generator.generateFromPromoted(catchupCs, workingDir);
publishSkillDraftCreatedEvents(summary, workingDir, "startup-catchup");
if (summary.createdDrafts() > 0) {
log.info("Draft catch-up: {} new drafts generated for existing promoted candidates",
summary.createdDrafts());
}
if (catchupValidation != null && summary.createdDrafts() > 0) {
var validation = catchupValidation.validateAll(workingDir, "startup-catchup");
publishSkillDraftValidationEvents(validation, workingDir, "startup-catchup");
if (catchupAutoRelease != null) {
var release = catchupAutoRelease.evaluateAll(workingDir, catchupCs, "startup-catchup");
publishSkillDraftReleaseEvents(release, workingDir, "startup-catchup");
}
}
} catch (Exception e) {
log.warn("Draft catch-up failed: {}", e.getMessage());
} finally {
draftPipelineLock.unlock();
}
});
}
}
dynamicSkillGenerator = new DynamicSkillGenerator(
llmClient,
agentHandler::getModelForSession,
skillRegistry);
dynamicSkillGenerator.setLearningExplanationRecorder(learningExplanationRecorder);
dynamicSkillGenerator.setLearningValidationRecorder(learningValidationRecorder);
agentHandler.setLearningExplanationRecorder(learningExplanationRecorder);
agentHandler.setLearningValidationRecorder(learningValidationRecorder);
agentHandler.setDynamicSkillGenerator(dynamicSkillGenerator);
// Wire deferred action scheduler (no turn lock dependency — uses isolated context)
if (config.deferredActionEnabled()) {
this.deferredActionScheduler = new DeferredActionScheduler(
deferredActionStore, sessionManager,
llmClient, toolRegistry, model, systemPrompt,
config.maxTokens(), config.thinkingBudget(),
eventBus, config.deferredActionTickSeconds());
deferCheckTool.setScheduler(deferredActionScheduler);
log.info("Deferred action scheduler wired (tick every {}s)",
config.deferredActionTickSeconds());
}
agentHandler.register(router);
// Session-end memory extraction + consolidation
// Runs SYNCHRONOUSLY to ensure extraction completes before session deactivation.
// This is critical during shutdown — async virtual threads may not finish before JVM exits.
// The extraction is pure-Java regex matching (no LLM calls), so blocking is fast.
final var extractionJournal = journal;
final var archiveDir = markdownStore != null ? markdownStore.memoryDir() : null;
final var agentHandlerForCleanup = agentHandler;
final var sessionAnalyzer = memoryStore != null ? new SessionAnalyzer() : null;
final var historicalIndexRebuilder = historicalLogIndex != null
? new HistoricalIndexRebuilder(historyStore, historicalLogIndex)
: null;
final var crossSessionPatternMiner = historicalLogIndex != null ? new CrossSessionPatternMiner() : null;
final var trendDetector = historicalLogIndex != null ? new TrendDetector() : null;
final var maintenanceCandidateBridge = config.candidatePromotionEnabled() && candidateStoreRef != null
? new LearningMaintenanceCandidateBridge(candidateStoreRef)
: null;
final var maintenanceCandidateStore = candidateStoreRef;
final var maintenanceValidationGate = validationGateEngine;
final var maintenanceAutoRelease = autoReleaseController;
if (memoryStore != null) {
learningMaintenanceScheduler = new LearningMaintenanceScheduler(
LearningMaintenanceScheduler.Config.defaults(Duration.ofSeconds(config.schedulerTickSeconds())),
java.time.Clock.systemUTC(),
sessionManager::sessionCount,
scopes -> scopes.stream()
.mapToLong(scope -> memoryStore.largestBackingFileBytes(scope.workingDir()))
.max()
.orElse(0L),
(trigger, scope) -> runLearningMaintenancePipeline(
trigger,
memoryStore,
archiveDir,
extractionJournal,
historicalIndexRebuilder,
crossSessionPatternMiner,
trendDetector,
maintenanceCandidateBridge,
maintenanceCandidateStore,
maintenanceValidationGate,
maintenanceAutoRelease,
draftPipelineLock,
scope.workspaceHash(),
scope.workingDir()),
learningMaintenanceRecoveryStore
);
}
final var runtimeSkillGeneratorForSessionEnd = dynamicSkillGenerator;
final var permissionManagerForSessionEnd = permissionManager;
sessionManager.setSessionEndCallback(session -> {
// Drop this session's per-tool "remember" allow-list (issue #456).
// Without this, a long-lived daemon would accumulate allow-lists
// for ended sessions indefinitely; more importantly, a sessionId
// re-issued by the OS later would inherit the previous owner's
// approvals — unlikely in practice but worth keeping clean.
permissionManagerForSessionEnd.clearSessionApprovals(session.id());
// Notify dashboard FIRST so the sidebar transitions immediately —
// the rest of this callback (memory extraction, history flush,
// learning analysis, runtime-skill-draft persistence, …) can take
// multiple seconds and the user shouldn't watch a stale "active"
// dot the whole time. SessionManager has already removed the
// session from its map by the time this runs, so the broadcast is
// honest about the daemon's view of state.
//
// reason carries the daemon's lifecycle context: the running flag
// is true for normal session.destroy calls and false during
// shutdownManager.executeShutdown(), so the dashboard can
// distinguish "user closed this one session" from "daemon is
// going down" without an extra round-trip.
var bridge = this.webSocketBridge;
if (bridge != null) {
try {
var params = objectMapper.createObjectNode();
params.put("sessionId", session.id());
params.put("timestamp", java.time.Instant.now().toString());
params.put("reason", running ? "destroyed" : "shutdown");
bridge.broadcast(session.id(), "stream.session_ended", params);
} catch (Exception e) {
log.warn("Failed to broadcast stream.session_ended for {}: {}",
session.id(), e.getMessage());
}
// Drop the snapshot buffer for this session (issue #432). The
// session_ended event was just buffered above, so a tab that
// opens between this point and the buffer being cleared still
// gets a snapshot containing session_ended; afterward the
// session is gone from sessionManager, so sessions.list won't
// surface it and snapshot.request returns an empty list.
bridge.clearSession(session.id());
}
if (memoryStore != null) {
var sessionWorkingDir = session.projectPath().toAbsolutePath().normalize();
var sessionWorkspaceHash = WorkspacePaths.workspaceHash(sessionWorkingDir);
historyStore.saveSession(session);
var extracted = SessionEndExtractor.extract(session.messages());
for (var mem : extracted) {
try {
memoryStore.add(mem.category(), mem.content(), mem.tags(),
"session-end:" + session.id(), false, sessionWorkingDir);
} catch (Exception e) {
log.warn("Failed to save session-end memory: {}", e.getMessage());
}
}
if (!extracted.isEmpty()) {
log.info("Extracted {} memories from session {} on destroy",
extracted.size(), session.id());
}
var metricsSnapshot = agentHandlerForCleanup.snapshotSessionMetrics(session.id());
var learnings = sessionAnalyzer.analyze(session.messages(), metricsSnapshot);
for (var insight : learnings.insights()) {
if (!shouldPersistSessionAnalysisInsight(insight)) {
continue;
}
try {
memoryStore.addIfAbsent(
insight.category(),
insight.content(),
insight.tags(),
"session-analysis:" + session.id(),
false,
sessionWorkingDir);
learningExplanationRecorder.recordMemoryWrite(
sessionWorkingDir,
session.id(),
"session-analysis",
insight.category(),
insight.content(),
insight.tags(),
List.of(new LearningExplanation.EvidenceRef(
"session-summary",
session.id(),
learnings.sessionSummary())));
} catch (Exception e) {
log.warn("Failed to save session analysis memory: {}", e.getMessage());
}
}
var shortId = session.id().length() > 8
? session.id().substring(0, 8) : session.id();
if (extractionJournal != null) {
extractionJournal.append("Session " + shortId +
" ended: " + session.messages().size() + " messages, " +
extracted.size() + " memories extracted");
if (!learnings.sessionSummary().isBlank()) {
extractionJournal.append("Session retrospective (" + shortId + "): "
+ learnings.sessionSummary());
}
}
if (historicalLogIndex != null) {
try {
var snapshot = new HistoricalSessionSnapshot(
session.id(),
sessionWorkspaceHash,
Instant.now(),
learnings.executedCommands(),
learnings.errorsEncountered(),
learnings.extractedFilePaths(),
metricsSnapshot,
learnings.backtrackingDetected(),
learnings.endToEndStrategy()
);
historyStore.saveSnapshot(snapshot);
historicalLogIndex.index(snapshot);
} catch (Exception e) {
log.warn("Failed to index session history: {}", e.getMessage());
}
}
if (learningMaintenanceScheduler != null) {
try {
learningMaintenanceScheduler.onSessionClosed(sessionWorkspaceHash, sessionWorkingDir);
} catch (Exception e) {
log.warn("Learning maintenance trigger failed: {}", e.getMessage());