-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathConversationRuntime.cs
More file actions
1510 lines (1363 loc) · 61.4 KB
/
ConversationRuntime.cs
File metadata and controls
1510 lines (1363 loc) · 61.4 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
using System.Collections.Concurrent;
using System.Globalization;
using System.Text.Json;
using Microsoft.Extensions.Logging;
using SharpClaw.Code.Infrastructure.Abstractions;
using SharpClaw.Code.Providers.Models;
using SharpClaw.Code.Protocol.Commands;
using SharpClaw.Code.Protocol.Enums;
using SharpClaw.Code.Protocol.Events;
using SharpClaw.Code.Protocol.Models;
using SharpClaw.Code.Protocol.Operational;
using SharpClaw.Code.Protocol.Serialization;
using SharpClaw.Code.Runtime.Abstractions;
using SharpClaw.Code.Runtime.CustomCommands;
using SharpClaw.Code.Runtime.Diagnostics;
using SharpClaw.Code.Runtime.Export;
using SharpClaw.Code.Runtime.Context;
using SharpClaw.Code.Runtime.Lifecycle;
using SharpClaw.Code.Runtime.Mutations;
using SharpClaw.Code.Runtime.Turns;
using SharpClaw.Code.Runtime.Workflow;
using SharpClaw.Code.Sessions.Abstractions;
using SharpClaw.Code.Sessions.Storage;
using SharpClaw.Code.Telemetry;
using SharpClaw.Code.Telemetry.Abstractions;
namespace SharpClaw.Code.Runtime.Orchestration;
/// <summary>
/// Implements durable conversation runtime orchestration for prompt execution.
/// </summary>
public sealed class ConversationRuntime(
ISessionStore sessionStore,
IEventStore eventStore,
IRuntimeEventPublisher eventPublisher,
ICheckpointStore checkpointStore,
ITurnRunner turnRunner,
IRuntimeStateMachine stateMachine,
ISystemClock systemClock,
IFileSystem fileSystem,
IPathService pathService,
IOperationalDiagnosticsCoordinator operationalDiagnostics,
ICustomCommandDiscoveryService customCommandDiscovery,
ISessionExportService sessionExportService,
IWorkspaceSessionAttachmentStore workspaceSessionAttachmentStore,
IEditorContextBuffer editorContextBuffer,
CheckpointMutationCoordinator checkpointMutationCoordinator,
ISessionCoordinator sessionCoordinator,
IPortableSessionBundleService portableSessionBundleService,
ISpecWorkflowService specWorkflowService,
ISharpClawConfigService sharpClawConfigService,
IAgentCatalogService agentCatalogService,
IShareSessionService shareSessionService,
IConversationCompactionService conversationCompactionService,
IHookDispatcher hookDispatcher,
ILogger<ConversationRuntime> logger) : IConversationRuntime, IRuntimeCommandService
{
private const string LastTurnSequenceKey = "lastTurnSequence";
private const string CanceledTurnReason = "The turn was canceled.";
private const string FailedTurnReason = "The turn failed.";
private static readonly ConcurrentDictionary<string, SemaphoreSlim> SessionMutexes = new(StringComparer.Ordinal);
private static SemaphoreSlim GetSessionMutex(string workspacePath, string sessionId)
=> SessionMutexes.GetOrAdd($"{workspacePath}\u0000{sessionId}", static _ => new SemaphoreSlim(1, 1));
/// <inheritdoc />
public async Task<ConversationSession> CreateSessionAsync(string workspacePath, PermissionMode permissionMode, OutputFormat outputFormat, CancellationToken cancellationToken)
{
var normalizedWorkspacePath = NormalizeWorkspacePath(workspacePath);
fileSystem.CreateDirectory(pathService.Combine(normalizedWorkspacePath, ".sharpclaw"));
var sessionId = CreateIdentifier("session");
var session = new ConversationSession(
Id: sessionId,
Title: $"Session {sessionId[..8]}",
State: SessionLifecycleState.Created,
PermissionMode: permissionMode,
OutputFormat: outputFormat,
WorkingDirectory: normalizedWorkspacePath,
RepositoryRoot: normalizedWorkspacePath,
CreatedAtUtc: systemClock.UtcNow,
UpdatedAtUtc: systemClock.UtcNow,
ActiveTurnId: null,
LastCheckpointId: null,
Metadata: new Dictionary<string, string>
{
[LastTurnSequenceKey] = "0"
});
await sessionStore.SaveAsync(normalizedWorkspacePath, session, cancellationToken).ConfigureAwait(false);
return session;
}
/// <inheritdoc />
public Task<ConversationSession?> GetSessionAsync(string workspacePath, string sessionId, CancellationToken cancellationToken)
=> sessionStore.GetByIdAsync(NormalizeWorkspacePath(workspacePath), sessionId, cancellationToken);
/// <inheritdoc />
public Task<ConversationSession?> GetLatestSessionAsync(string workspacePath, CancellationToken cancellationToken)
=> sessionStore.GetLatestAsync(NormalizeWorkspacePath(workspacePath), cancellationToken);
/// <inheritdoc />
public async Task<TurnExecutionResult> RunPromptAsync(RunPromptRequest request, CancellationToken cancellationToken)
{
ArgumentException.ThrowIfNullOrWhiteSpace(request.Prompt);
var workspacePath = NormalizeWorkspacePath(request.WorkingDirectory);
request = EnrichRequestWithEditorIngress(workspacePath, request);
request = await ApplyAgentAndConfigDefaultsAsync(workspacePath, request, cancellationToken).ConfigureAwait(false);
var runtimeEvents = new List<RuntimeEvent>();
var session = await ResolveSessionAsync(workspacePath, request, cancellationToken).ConfigureAwait(false);
var isNewSession = false;
if (session is null)
{
session = await CreateSessionAsync(workspacePath, request.PermissionMode, request.OutputFormat, cancellationToken).ConfigureAwait(false);
isNewSession = true;
}
if (request.SessionId is not null && !string.Equals(session.Id, request.SessionId, StringComparison.Ordinal))
{
throw new InvalidOperationException($"Unable to resume session '{request.SessionId}'.");
}
session = await EnsurePrimaryModePersistedAsync(workspacePath, session, request.PrimaryMode, cancellationToken).ConfigureAwait(false);
var sessionMutex = GetSessionMutex(workspacePath, session.Id);
await sessionMutex.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
var turnLockPath = SessionStorageLayout.GetSessionTurnLockPath(pathService, workspacePath, session.Id);
await using var crossProcessTurnLock = await fileSystem
.AcquireExclusiveFileLockAsync(turnLockPath, cancellationToken)
.ConfigureAwait(false);
// Re-read the session inside the lock so the turn sequence read-modify-write is consistent across concurrent prompts.
var refreshed = await sessionStore.GetByIdAsync(workspacePath, session.Id, cancellationToken).ConfigureAwait(false);
if (refreshed is not null)
{
session = refreshed;
}
session = await EnsureRecoverableFromFailedForPromptAsync(
workspacePath,
session,
runtimeEvents,
cancellationToken)
.ConfigureAwait(false);
if (isNewSession)
{
await AppendEventAsync(
workspacePath,
session.Id,
new SessionCreatedEvent(
EventId: CreateIdentifier("event"),
SessionId: session.Id,
TurnId: null,
OccurredAtUtc: systemClock.UtcNow,
Session: session),
runtimeEvents,
cancellationToken).ConfigureAwait(false);
}
var previousState = session.State;
var activeState = stateMachine.Transition(session.State, RuntimeLifecycleTransition.Activate);
if (previousState != activeState)
{
session = session with
{
State = activeState,
UpdatedAtUtc = systemClock.UtcNow,
};
await AppendEventAsync(
workspacePath,
session.Id,
new SessionStateChangedEvent(
EventId: CreateIdentifier("event"),
SessionId: session.Id,
TurnId: null,
OccurredAtUtc: systemClock.UtcNow,
PreviousState: previousState,
CurrentState: activeState,
Reason: "Prompt execution activated the session."),
runtimeEvents,
cancellationToken).ConfigureAwait(false);
}
var turnSequenceNumber = GetLastTurnSequence(session) + 1;
var turnId = CreateIdentifier("turn");
var startedAtUtc = systemClock.UtcNow;
var primaryAgentId = string.IsNullOrWhiteSpace(request.AgentId) ? "primary-coding-agent" : request.AgentId!;
var turn = new ConversationTurn(
Id: turnId,
SessionId: session.Id,
SequenceNumber: turnSequenceNumber,
Input: request.Prompt,
Output: null,
StartedAtUtc: startedAtUtc,
CompletedAtUtc: null,
AgentId: primaryAgentId,
SlashCommandName: null,
Usage: null,
Metadata: new Dictionary<string, string>
{
["workspacePath"] = workspacePath,
["resumeMode"] = request.SessionId is null ? "latest-or-create" : "explicit"
});
var metadataAtTurnStart = CloneMetadata(session.Metadata);
metadataAtTurnStart[LastTurnSequenceKey] = turnSequenceNumber.ToString(CultureInfo.InvariantCulture);
metadataAtTurnStart["lastTurnId"] = turnId;
if (!string.IsNullOrWhiteSpace(request.AgentId))
{
metadataAtTurnStart[SharpClawWorkflowMetadataKeys.ActiveAgentId] = request.AgentId!;
}
session = session with
{
ActiveTurnId = turnId,
UpdatedAtUtc = startedAtUtc,
Metadata = metadataAtTurnStart,
};
// Persist sequence allocation before any cancellable I/O so failed/canceled turns
// still monotonically consume sequence numbers even if the event append is cancelled.
await sessionStore.SaveAsync(workspacePath, session, CancellationToken.None).ConfigureAwait(false);
await AppendEventAsync(
workspacePath,
session.Id,
new TurnStartedEvent(
EventId: CreateIdentifier("event"),
SessionId: session.Id,
TurnId: turnId,
OccurredAtUtc: startedAtUtc,
Turn: turn),
runtimeEvents,
cancellationToken).ConfigureAwait(false);
try
{
var effectivePrimary = PrimaryModeResolver.ResolveEffective(request, session);
var runnerRequest = request with
{
WorkingDirectory = workspacePath,
Metadata = MergeMetadata(request.Metadata, request.PermissionMode, request.OutputFormat, effectivePrimary)
};
var turnRunResult = await turnRunner.RunAsync(session, turn, runnerRequest, cancellationToken).ConfigureAwait(false);
SpecArtifactSet? specArtifacts = null;
if (effectivePrimary == PrimaryMode.Spec)
{
specArtifacts = await specWorkflowService
.MaterializeAsync(workspacePath, request.Prompt, turnRunResult.Output, cancellationToken)
.ConfigureAwait(false);
turnRunResult = turnRunResult with
{
Output = FormatSpecCompletionMessage(specArtifacts),
Summary = $"Generated spec artifacts in '{specArtifacts.RootPath}'."
};
}
var completedAtUtc = systemClock.UtcNow;
var completedTurn = turn with
{
Output = turnRunResult.Output,
CompletedAtUtc = completedAtUtc,
Usage = turnRunResult.Usage,
};
ConversationHistoryCache.StoreCompletedTurn(workspacePath, session.Id, completedTurn);
await AppendRuntimeEventsAsync(
workspacePath,
session.Id,
turnRunResult.RuntimeEvents,
runtimeEvents,
cancellationToken).ConfigureAwait(false);
await AppendProviderEventsAsync(
workspacePath,
session.Id,
turnId,
turnRunResult,
runtimeEvents,
cancellationToken).ConfigureAwait(false);
await AppendEventAsync(
workspacePath,
session.Id,
new UsageUpdatedEvent(
EventId: CreateIdentifier("event"),
SessionId: session.Id,
TurnId: turnId,
OccurredAtUtc: completedAtUtc,
Usage: turnRunResult.Usage),
runtimeEvents,
cancellationToken).ConfigureAwait(false);
var checkpointId = CreateIdentifier("checkpoint");
var checkpoint = new RuntimeCheckpoint(
Id: checkpointId,
SessionId: session.Id,
TurnId: turnId,
CreatedAtUtc: completedAtUtc,
Summary: turnRunResult.Summary,
StateLocation: pathService.Combine(".sharpclaw", "sessions", session.Id, "checkpoints", $"{checkpointId}.json"),
RecoveryHint: "Resume the latest session to continue the conversation.",
Metadata: new Dictionary<string, string>
{
["turnSequence"] = turnSequenceNumber.ToString(CultureInfo.InvariantCulture)
});
await checkpointStore.SaveAsync(workspacePath, checkpoint, cancellationToken).ConfigureAwait(false);
var metadata = CloneMetadata(session.Metadata);
metadata[LastTurnSequenceKey] = turnSequenceNumber.ToString(CultureInfo.InvariantCulture);
metadata["lastTurnId"] = turnId;
if (!string.IsNullOrWhiteSpace(request.AgentId))
{
metadata[SharpClawWorkflowMetadataKeys.ActiveAgentId] = request.AgentId!;
}
session = session with
{
State = activeState,
UpdatedAtUtc = completedAtUtc,
ActiveTurnId = null,
LastCheckpointId = checkpoint.Id,
Metadata = metadata,
};
if (turnRunResult.FileMutations is { Count: > 0 } mutations)
{
session = await checkpointMutationCoordinator
.ApplyRecordedMutationsAsync(
workspacePath,
session,
turnId,
checkpointId,
mutations,
cancellationToken)
.ConfigureAwait(false);
}
await AppendEventAsync(
workspacePath,
session.Id,
new TurnCompletedEvent(
EventId: CreateIdentifier("event"),
SessionId: session.Id,
TurnId: turnId,
OccurredAtUtc: completedAtUtc,
Turn: completedTurn,
Succeeded: true,
Summary: turnRunResult.Summary),
runtimeEvents,
cancellationToken).ConfigureAwait(false);
await sessionStore.SaveAsync(workspacePath, session, cancellationToken).ConfigureAwait(false);
logger.LogInformation("Completed prompt turn {TurnId} for session {SessionId}.", turnId, session.Id);
SpecArtifactSet? finalSpecArtifacts = specArtifacts;
if (await ShouldAutoShareAsync(workspacePath, cancellationToken).ConfigureAwait(false))
{
try
{
var share = await shareSessionService.CreateShareAsync(workspacePath, session.Id, cancellationToken).ConfigureAwait(false);
session = await sessionStore.GetByIdAsync(workspacePath, session.Id, cancellationToken).ConfigureAwait(false) ?? session;
finalSpecArtifacts = specArtifacts;
runtimeEvents.Add(
new ShareCreatedEvent(
EventId: CreateIdentifier("event"),
SessionId: session.Id,
TurnId: turnId,
OccurredAtUtc: share.CreatedAtUtc,
Share: share));
}
catch (Exception exception)
{
logger.LogWarning(exception, "Auto-share failed for session {SessionId}.", session.Id);
}
}
return new TurnExecutionResult(
Session: session,
Turn: completedTurn,
FinalOutput: completedTurn.Output,
ToolResults: (turnRunResult.ToolResults ?? []).ToArray(),
Usage: turnRunResult.Usage,
Checkpoint: checkpoint,
Events: runtimeEvents.ToArray(),
SpecArtifacts: finalSpecArtifacts);
}
catch (OperationCanceledException exception)
{
session = await PersistTurnFailureAsync(
workspacePath,
session,
turnId,
runtimeEvents,
CanceledTurnReason,
CancellationToken.None).ConfigureAwait(false);
logger.LogWarning(
exception,
"Prompt execution was canceled for session {SessionId}, turn {TurnId}.",
session.Id,
turnId);
throw;
}
catch (ProviderExecutionException exception)
{
session = await PersistTurnFailureAsync(
workspacePath,
session,
turnId,
runtimeEvents,
FormatProviderFailureReason(exception),
CancellationToken.None).ConfigureAwait(false);
logger.LogError(
exception,
"Prompt execution failed due to provider error {FailureKind} for session {SessionId}, turn {TurnId}.",
exception.Kind,
session.Id,
turnId);
throw;
}
catch (Exception exception)
{
session = await PersistTurnFailureAsync(
workspacePath,
session,
turnId,
runtimeEvents,
string.IsNullOrWhiteSpace(exception.Message) ? FailedTurnReason : exception.Message,
CancellationToken.None).ConfigureAwait(false);
logger.LogError(
exception,
"Prompt execution failed for session {SessionId}, turn {TurnId}.",
session.Id,
turnId);
throw;
}
}
finally
{
sessionMutex.Release();
}
}
/// <inheritdoc />
public Task<TurnExecutionResult> ExecutePromptAsync(string prompt, RuntimeCommandContext context, CancellationToken cancellationToken)
=> RunPromptAsync(
new RunPromptRequest(
Prompt: prompt,
SessionId: context.SessionId,
WorkingDirectory: context.WorkingDirectory,
PermissionMode: context.PermissionMode,
OutputFormat: context.OutputFormat,
Metadata: new Dictionary<string, string?>
{
["model"] = context.Model
}
.Where(pair => pair.Value is not null)
.ToDictionary(pair => pair.Key, pair => pair.Value!),
PrimaryMode: context.PrimaryMode,
AgentId: context.AgentId,
IsInteractive: context.IsInteractive),
cancellationToken);
/// <inheritdoc />
public async Task<TurnExecutionResult> ExecuteCustomCommandAsync(
string commandName,
string arguments,
RuntimeCommandContext context,
CancellationToken cancellationToken)
{
ArgumentException.ThrowIfNullOrWhiteSpace(commandName);
var workspace = NormalizeWorkspacePath(context.WorkingDirectory);
var definition = await customCommandDiscovery
.FindAsync(workspace, commandName, cancellationToken)
.ConfigureAwait(false)
?? throw new InvalidOperationException($"Unknown custom command '{commandName}'.");
var expanded = CustomCommandTemplateExpander.Expand(definition.TemplateBody, arguments.Trim());
var metadata = new Dictionary<string, string>(StringComparer.Ordinal);
if (!string.IsNullOrWhiteSpace(context.Model))
{
metadata["model"] = context.Model!;
}
if (!string.IsNullOrWhiteSpace(definition.Model))
{
metadata["model"] = definition.Model;
}
metadata[SharpClawWorkflowMetadataKeys.CustomCommandName] = definition.Name;
var permission = ClampPermissionModeForCustomCommand(context.PermissionMode, definition.PermissionMode);
var contextPrimary = context.PrimaryMode ?? PrimaryMode.Build;
var primary = ClampPrimaryModeForCustomCommand(contextPrimary, definition.PrimaryModeOverride);
return await RunPromptAsync(
new RunPromptRequest(
Prompt: expanded,
SessionId: context.SessionId,
WorkingDirectory: workspace,
PermissionMode: permission,
OutputFormat: context.OutputFormat,
Metadata: metadata,
PrimaryMode: primary,
AgentId: definition.AgentId,
IsInteractive: context.IsInteractive),
cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc />
public async Task<CommandResult> GetStatusAsync(RuntimeCommandContext context, CancellationToken cancellationToken)
{
var input = new OperationalDiagnosticsInput(
context.WorkingDirectory,
context.Model,
context.PermissionMode,
context.OutputFormat,
context.PrimaryMode);
var report = await operationalDiagnostics
.BuildStatusReportAsync(input, cancellationToken)
.ConfigureAwait(false);
var payload = JsonSerializer.Serialize(report, ProtocolJsonContext.Default.RuntimeStatusReport);
var message = FormatStatusMessage(report);
return new CommandResult(
Succeeded: true,
ExitCode: 0,
OutputFormat: context.OutputFormat,
Message: message,
DataJson: payload);
}
/// <inheritdoc />
public async Task<CommandResult> RunDoctorAsync(RuntimeCommandContext context, CancellationToken cancellationToken)
{
var input = new OperationalDiagnosticsInput(
context.WorkingDirectory,
context.Model,
context.PermissionMode,
context.OutputFormat,
context.PrimaryMode);
var report = await operationalDiagnostics.RunDoctorAsync(input, cancellationToken).ConfigureAwait(false);
var payload = JsonSerializer.Serialize(report, ProtocolJsonContext.Default.DoctorReport);
var exitCode = report.OverallStatus == OperationalCheckStatus.Error ? 1 : 0;
var message = FormatDoctorMessage(report);
return new CommandResult(
Succeeded: exitCode == 0,
ExitCode: exitCode,
OutputFormat: context.OutputFormat,
Message: message,
DataJson: payload);
}
/// <inheritdoc />
public async Task<CommandResult> InspectSessionAsync(string? sessionId, RuntimeCommandContext context, CancellationToken cancellationToken)
{
var input = new OperationalDiagnosticsInput(
context.WorkingDirectory,
context.Model,
context.PermissionMode,
context.OutputFormat,
context.PrimaryMode);
var inspection = await operationalDiagnostics
.InspectSessionAsync(sessionId, input, cancellationToken)
.ConfigureAwait(false);
if (inspection is null)
{
return new CommandResult(
Succeeded: false,
ExitCode: 1,
OutputFormat: context.OutputFormat,
Message: "No matching session found.",
DataJson: null);
}
var payload = JsonSerializer.Serialize(inspection, ProtocolJsonContext.Default.SessionInspectionReport);
var message =
$"{inspection.Session.Id} ({inspection.Session.State}) · {inspection.PersistedEventCount} persisted events";
return new CommandResult(
Succeeded: true,
ExitCode: 0,
OutputFormat: context.OutputFormat,
Message: message,
DataJson: payload);
}
/// <inheritdoc />
public async Task<CommandResult> ForkSessionAsync(
string? sourceSessionId,
RuntimeCommandContext context,
CancellationToken cancellationToken)
{
try
{
var child = await ForkSessionAsync(NormalizeWorkspacePath(context.WorkingDirectory), sourceSessionId, cancellationToken)
.ConfigureAwait(false);
var payload = JsonSerializer.Serialize(child, ProtocolJsonContext.Default.ConversationSession);
return new CommandResult(
true,
0,
context.OutputFormat,
$"Forked session {child.Id} from '{child.Metadata?.GetValueOrDefault(SharpClawWorkflowMetadataKeys.ParentSessionId) ?? "?"}'.",
payload);
}
catch (Exception ex)
{
return new CommandResult(false, 1, context.OutputFormat, ex.Message, null);
}
}
/// <inheritdoc />
public async Task<CommandResult> ExportSessionAsync(
string? sessionId,
SessionExportFormat format,
string? outputFilePath,
RuntimeCommandContext context,
CancellationToken cancellationToken)
{
try
{
var workspace = NormalizeWorkspacePath(context.WorkingDirectory);
var (document, ext) = await sessionExportService
.BuildDocumentAsync(workspace, sessionId, format, cancellationToken)
.ConfigureAwait(false);
var exportsDir = pathService.Combine(workspace, ".sharpclaw", "exports");
fileSystem.CreateDirectory(exportsDir);
var fileName =
$"{document.Session.Id}-{document.ExportedAtUtc:yyyyMMddTHHmmss}.{ext}";
var targetPath = string.IsNullOrWhiteSpace(outputFilePath)
? pathService.Combine(exportsDir, fileName)
: pathService.GetFullPath(outputFilePath);
var text = format == SessionExportFormat.Json
? JsonSerializer.Serialize(document, ProtocolJsonContext.Default.SessionExportDocument)
: sessionExportService.RenderMarkdown(document);
await fileSystem.WriteAllTextAsync(targetPath, text, cancellationToken).ConfigureAwait(false);
return new CommandResult(
true,
0,
context.OutputFormat,
$"Exported session to '{targetPath}'.",
JsonSerializer.Serialize(
new Dictionary<string, string> { ["path"] = targetPath, ["format"] = ext },
ProtocolJsonContext.Default.DictionaryStringString));
}
catch (Exception ex)
{
return new CommandResult(false, 1, context.OutputFormat, ex.Message, null);
}
}
/// <inheritdoc />
public async Task<CommandResult> UndoAsync(string? sessionId, RuntimeCommandContext context, CancellationToken cancellationToken)
{
try
{
var workspace = NormalizeWorkspacePath(context.WorkingDirectory);
var sid = await ResolveCommandSessionIdAsync(workspace, sessionId, context.SessionId, cancellationToken).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(sid))
{
return new CommandResult(false, 1, context.OutputFormat, "No session resolved for undo.", null);
}
var result = await checkpointMutationCoordinator
.TryUndoAsync(
workspace,
sid,
cancellationToken,
operation => ExecuteWithSessionLockAsync(workspace, sid, operation, cancellationToken))
.ConfigureAwait(false);
var payload = JsonSerializer.Serialize(result, ProtocolJsonContext.Default.UndoRedoActionResult);
return new CommandResult(result.Succeeded, result.Succeeded ? 0 : 1, context.OutputFormat, result.Message, payload);
}
catch (Exception ex)
{
return new CommandResult(false, 1, context.OutputFormat, ex.Message, null);
}
}
/// <inheritdoc />
public async Task<CommandResult> RedoAsync(string? sessionId, RuntimeCommandContext context, CancellationToken cancellationToken)
{
try
{
var workspace = NormalizeWorkspacePath(context.WorkingDirectory);
var sid = await ResolveCommandSessionIdAsync(workspace, sessionId, context.SessionId, cancellationToken).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(sid))
{
return new CommandResult(false, 1, context.OutputFormat, "No session resolved for redo.", null);
}
var result = await checkpointMutationCoordinator
.TryRedoAsync(
workspace,
sid,
cancellationToken,
operation => ExecuteWithSessionLockAsync(workspace, sid, operation, cancellationToken))
.ConfigureAwait(false);
var payload = JsonSerializer.Serialize(result, ProtocolJsonContext.Default.UndoRedoActionResult);
return new CommandResult(result.Succeeded, result.Succeeded ? 0 : 1, context.OutputFormat, result.Message, payload);
}
catch (Exception ex)
{
return new CommandResult(false, 1, context.OutputFormat, ex.Message, null);
}
}
/// <inheritdoc />
public async Task<CommandResult> ExportPortableSessionBundleAsync(
string? sessionId,
string? outputZipPath,
RuntimeCommandContext context,
CancellationToken cancellationToken)
{
try
{
var workspace = NormalizeWorkspacePath(context.WorkingDirectory);
var path = await portableSessionBundleService
.CreateBundleZipAsync(workspace, sessionId, outputZipPath, cancellationToken)
.ConfigureAwait(false);
return new CommandResult(
true,
0,
context.OutputFormat,
$"Portable bundle written to '{path}'.",
JsonSerializer.Serialize(
new Dictionary<string, string> { ["path"] = path },
ProtocolJsonContext.Default.DictionaryStringString));
}
catch (Exception ex)
{
return new CommandResult(false, 1, context.OutputFormat, ex.Message, null);
}
}
/// <inheritdoc />
public async Task<CommandResult> ImportPortableSessionBundleAsync(
string bundleZipPath,
bool replaceExisting,
bool attachAfterImport,
RuntimeCommandContext context,
CancellationToken cancellationToken)
{
try
{
var workspace = NormalizeWorkspacePath(context.WorkingDirectory);
var zip = pathService.GetFullPath(bundleZipPath);
var result = await portableSessionBundleService
.ImportBundleZipAsync(workspace, zip, replaceExisting, cancellationToken)
.ConfigureAwait(false);
if (attachAfterImport)
{
await sessionCoordinator.AttachSessionAsync(workspace, result.SessionId, cancellationToken).ConfigureAwait(false);
}
var message = attachAfterImport
? $"Imported session '{result.SessionId}' and attached it for this workspace."
: $"Imported session '{result.SessionId}'.";
var payload = JsonSerializer.Serialize(result, ProtocolJsonContext.Default.PortableBundleImportResult);
return new CommandResult(true, 0, context.OutputFormat, message, payload);
}
catch (Exception ex)
{
return new CommandResult(false, 1, context.OutputFormat, ex.Message, null);
}
}
/// <inheritdoc />
public async Task<CommandResult> ListSessionsAsync(RuntimeCommandContext context, CancellationToken cancellationToken)
{
try
{
var workspace = NormalizeWorkspacePath(context.WorkingDirectory);
var rows = await sessionCoordinator.ListSessionsAsync(workspace, cancellationToken).ConfigureAwait(false);
var payload = JsonSerializer.Serialize(rows, ProtocolJsonContext.Default.ListSessionSummaryRow);
return new CommandResult(true, 0, context.OutputFormat, $"{rows.Count} session(s).", payload);
}
catch (Exception ex)
{
return new CommandResult(false, 1, context.OutputFormat, ex.Message, null);
}
}
/// <inheritdoc />
public async Task<CommandResult> AttachSessionAsync(string sessionId, RuntimeCommandContext context, CancellationToken cancellationToken)
{
try
{
var workspace = NormalizeWorkspacePath(context.WorkingDirectory);
await sessionCoordinator.AttachSessionAsync(workspace, sessionId, cancellationToken).ConfigureAwait(false);
return new CommandResult(
true,
0,
context.OutputFormat,
$"Attached session '{sessionId}' for workspace prompts.",
JsonSerializer.Serialize(
new Dictionary<string, string> { ["sessionId"] = sessionId },
ProtocolJsonContext.Default.DictionaryStringString));
}
catch (Exception ex)
{
return new CommandResult(false, 1, context.OutputFormat, ex.Message, null);
}
}
/// <inheritdoc />
public async Task<CommandResult> DetachSessionAsync(RuntimeCommandContext context, CancellationToken cancellationToken)
{
try
{
var workspace = NormalizeWorkspacePath(context.WorkingDirectory);
await sessionCoordinator.DetachSessionAsync(workspace, cancellationToken).ConfigureAwait(false);
return new CommandResult(true, 0, context.OutputFormat, "Detached explicit workspace session.", null);
}
catch (Exception ex)
{
return new CommandResult(false, 1, context.OutputFormat, ex.Message, null);
}
}
/// <inheritdoc />
public async Task<CommandResult> ShareSessionAsync(string? sessionId, RuntimeCommandContext context, CancellationToken cancellationToken)
{
try
{
var workspace = NormalizeWorkspacePath(context.WorkingDirectory);
var sid = await ResolveCommandSessionIdAsync(workspace, sessionId, context.SessionId, cancellationToken).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(sid))
{
return new CommandResult(false, 1, context.OutputFormat, "No session resolved for sharing.", null);
}
var share = await ExecuteWithSessionLockAsync(
workspace,
sid,
ct => shareSessionService.CreateShareAsync(workspace, sid, ct),
cancellationToken)
.ConfigureAwait(false);
var payload = JsonSerializer.Serialize(share, ProtocolJsonContext.Default.ShareSessionRecord);
return new CommandResult(true, 0, context.OutputFormat, $"Shared session '{sid}' at {share.Url}.", payload);
}
catch (Exception ex)
{
return new CommandResult(false, 1, context.OutputFormat, ex.Message, null);
}
}
/// <inheritdoc />
public async Task<CommandResult> UnshareSessionAsync(string? sessionId, RuntimeCommandContext context, CancellationToken cancellationToken)
{
try
{
var workspace = NormalizeWorkspacePath(context.WorkingDirectory);
var sid = await ResolveCommandSessionIdAsync(workspace, sessionId, context.SessionId, cancellationToken).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(sid))
{
return new CommandResult(false, 1, context.OutputFormat, "No session resolved for unshare.", null);
}
var removed = await ExecuteWithSessionLockAsync(
workspace,
sid,
ct => shareSessionService.RemoveShareAsync(workspace, sid, ct),
cancellationToken)
.ConfigureAwait(false);
return new CommandResult(
removed,
removed ? 0 : 1,
context.OutputFormat,
removed ? $"Removed share for session '{sid}'." : $"Session '{sid}' is not currently shared.",
null);
}
catch (Exception ex)
{
return new CommandResult(false, 1, context.OutputFormat, ex.Message, null);
}
}
/// <inheritdoc />
public async Task<CommandResult> CompactSessionAsync(string? sessionId, RuntimeCommandContext context, CancellationToken cancellationToken)
{
try
{
var workspace = NormalizeWorkspacePath(context.WorkingDirectory);
var sid = await ResolveCommandSessionIdAsync(workspace, sessionId, context.SessionId, cancellationToken).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(sid))
{
return new CommandResult(false, 1, context.OutputFormat, "No session resolved for compaction.", null);
}
var result = await ExecuteWithSessionLockAsync(
workspace,
sid,
ct => conversationCompactionService.CompactAsync(workspace, sid, ct),
cancellationToken)
.ConfigureAwait(false);
var payload = JsonSerializer.Serialize(result.Session, ProtocolJsonContext.Default.ConversationSession);
return new CommandResult(true, 0, context.OutputFormat, result.Summary, payload);
}
catch (Exception ex)
{
return new CommandResult(false, 1, context.OutputFormat, ex.Message, null);
}
}
/// <inheritdoc />
public async Task<ConversationSession> ForkSessionAsync(string workspacePath, string? sourceSessionId, CancellationToken cancellationToken)
{
var normalized = NormalizeWorkspacePath(workspacePath);
var parent = string.IsNullOrWhiteSpace(sourceSessionId)
? await sessionStore.GetLatestAsync(normalized, cancellationToken).ConfigureAwait(false)
: await sessionStore.GetByIdAsync(normalized, sourceSessionId, cancellationToken).ConfigureAwait(false);
if (parent is null)
{
throw new InvalidOperationException("Source session was not found.");
}
var events = await eventStore.ReadAllAsync(normalized, parent.Id, cancellationToken).ConfigureAwait(false);
var summary = BuildForkHistorySummary(events);
fileSystem.CreateDirectory(pathService.Combine(normalized, ".sharpclaw"));
var childId = CreateIdentifier("session");
var md = CloneMetadata(parent.Metadata);
md.Remove(SharpClawWorkflowMetadataKeys.UndoRedoStateJson);
md.Remove(CheckpointMutationCoordinator.PartialMutationKey);
md[SharpClawWorkflowMetadataKeys.ParentSessionId] = parent.Id;
md[SharpClawWorkflowMetadataKeys.ForkedAtUtc] = systemClock.UtcNow.ToString("O", CultureInfo.InvariantCulture);
md[SharpClawWorkflowMetadataKeys.ForkHistorySummary] = summary;
md[LastTurnSequenceKey] = "0";
var child = new ConversationSession(
Id: childId,
Title: $"Fork of {parent.Id[..Math.Min(8, parent.Id.Length)]}",
State: SessionLifecycleState.Created,
PermissionMode: parent.PermissionMode,
OutputFormat: parent.OutputFormat,
WorkingDirectory: normalized,
RepositoryRoot: normalized,
CreatedAtUtc: systemClock.UtcNow,
UpdatedAtUtc: systemClock.UtcNow,
ActiveTurnId: null,
LastCheckpointId: null,
Metadata: md);
await sessionStore.SaveAsync(normalized, child, cancellationToken).ConfigureAwait(false);
await eventPublisher.PublishAsync(
new SessionForkedEvent(
EventId: CreateIdentifier("event"),
SessionId: childId,
TurnId: null,
OccurredAtUtc: systemClock.UtcNow,
ParentSessionId: parent.Id,
ChildSessionId: childId,
ForkedFromCheckpointId: parent.LastCheckpointId),
new RuntimeEventPublishOptions(normalized, childId, PersistToSessionStore: true),
cancellationToken).ConfigureAwait(false);
return child;
}
private static string BuildForkHistorySummary(IReadOnlyList<RuntimeEvent> events)
{
var completedTurns = events.OfType<TurnCompletedEvent>().Count();
return completedTurns == 0
? "Forked from parent session (no completed turns in persisted event log)."
: $"Forked from parent session with {completedTurns} completed turn(s) in the persisted log.";
}
private async Task<ConversationSession> EnsurePrimaryModePersistedAsync(
string workspacePath,
ConversationSession session,
PrimaryMode? mode,
CancellationToken cancellationToken)
{
if (mode is null)
{
return session;
}
var md = CloneMetadata(session.Metadata);
var text = mode.Value.ToString();
if (md.TryGetValue(SharpClawWorkflowMetadataKeys.PrimaryMode, out var current)
&& string.Equals(current, text, StringComparison.OrdinalIgnoreCase))
{