agentty 0.7.6

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
//! Session task execution helpers for process running, output capture, and
//! status persistence.

use std::path::Path;
use std::sync::{Arc, Mutex};

use askama::Template;
use tokio::sync::mpsc;

use crate::app::assist::{
    AssistContext, AssistPolicy, FailureTracker, append_assist_header, format_detail_lines,
    run_agent_assist,
};
use crate::app::session::{Clock, SessionError, unix_timestamp_from_system_time};
use crate::app::{AppEvent, SessionManager};
use crate::domain::agent::AgentModel;
use crate::domain::session::{SessionSize, Status};
use crate::domain::setting::SettingName;
use crate::infra::agent;
use crate::infra::db::Database;
use crate::infra::git::{self as git, GitClient};

const AUTO_COMMIT_ASSIST_POLICY: AssistPolicy = AssistPolicy {
    max_attempts: 10,
    max_identical_failure_streak: 3,
};
const SESSION_COMMIT_COAUTHORED_BY_AGENTTY_TRAILER: &str =
    "Co-Authored-By: [Agentty](https://github.com/agentty-xyz/agentty)";

/// Askama view model for rendering auto-commit recovery prompts.
#[derive(Template)]
#[template(path = "auto_commit_assist_prompt.md", escape = "none")]
struct AutoCommitAssistPromptTemplate<'a> {
    commit_error: &'a str,
}

/// Askama view model for rendering session commit-message generation prompts.
#[derive(Template)]
#[template(path = "session_commit_message_prompt.md", escape = "none")]
struct SessionCommitMessagePromptTemplate<'a> {
    current_commit_message: &'a str,
    diff: &'a str,
}

/// Stateless helpers for session process execution and output handling.
pub(crate) struct SessionTaskService;

/// Generated session commit details for one successful auto-commit run.
pub(crate) struct SessionCommitOutcome {
    /// Short hash of the rewritten or created `HEAD` commit.
    pub(crate) commit_hash: String,
    /// Canonical commit title/body stored on the session branch `HEAD`.
    pub(crate) commit_message: String,
}

/// Inputs needed to execute an agent-assisted edit task.
pub(crate) struct RunAgentAssistTaskInput {
    /// App event sender used for progress and status updates.
    pub(crate) app_event_tx: mpsc::UnboundedSender<AppEvent>,
    /// Shared process identifier slot used for cancellation.
    pub(crate) child_pid: Arc<Mutex<Option<u32>>>,
    /// Database handle used for output/status persistence.
    pub(crate) db: Database,
    /// Session worktree folder where the assist prompt runs.
    pub(crate) folder: std::path::PathBuf,
    /// Session identifier for persisted updates.
    pub(crate) id: String,
    /// Shared output buffer receiving incremental output.
    pub(crate) output: Arc<Mutex<String>>,
    /// One-shot assist prompt submitted to the agent.
    pub(crate) prompt: String,
    /// Session model used for agent metadata and parsing.
    pub(crate) session_model: AgentModel,
}

impl SessionTaskService {
    /// Recomputes and persists diff-derived size and line-count totals using
    /// the session worktree diff.
    ///
    /// Returns the recomputed size plus added/deleted line totals when the
    /// base-branch lookup and persistence both succeed.
    pub(crate) async fn refresh_persisted_session_diff_stats(
        db: &Database,
        git_client: &dyn GitClient,
        session_id: &str,
        folder: &Path,
    ) -> Option<(SessionSize, u64, u64)> {
        let base_branch = db
            .get_session_base_branch(session_id)
            .await
            .ok()
            .flatten()?;

        let (computed_size, added_lines, deleted_lines) =
            SessionManager::session_diff_stats_for_folder(git_client, folder, &base_branch).await;
        db.update_session_diff_stats(
            added_lines,
            deleted_lines,
            session_id,
            &computed_size.to_string(),
        )
        .await
        .ok()?;

        Some((computed_size, added_lines, deleted_lines))
    }

    /// Commits pending worktree changes and appends user-visible outcomes.
    ///
    /// Successful commit hashes, no-op commit notices, and commit errors are
    /// emitted into session output for user visibility. Commit-message
    /// generation and any auto-commit recovery prompt use the resolved
    /// auto-commit model for the session. Successful commits also request an
    /// immediate git-status refresh so footer ahead/behind counts do not wait
    /// for the background poller.
    pub(in crate::app) async fn handle_auto_commit(context: AssistContext) {
        match Self::commit_changes_with_assist(&context).await {
            Ok(Some(outcome)) => {
                SessionManager::update_session_title_from_commit_message(
                    &context.db,
                    &context.id,
                    &outcome.commit_message,
                    &context.app_event_tx,
                )
                .await;

                let message = format!("\n[Commit] committed with hash `{}`\n", outcome.commit_hash);
                Self::append_session_output(
                    &context.output,
                    &context.db,
                    &context.app_event_tx,
                    &context.id,
                    &message,
                )
                .await;
                Self::request_git_status_refresh(&context.app_event_tx);
            }
            Ok(None) => {
                let message = "\n[Commit] No changes to commit.\n";
                Self::append_session_output(
                    &context.output,
                    &context.db,
                    &context.app_event_tx,
                    &context.id,
                    message,
                )
                .await;
            }
            Err(commit_error) => {
                let message = format!("\n[Commit Error] {commit_error}\n");
                Self::append_session_output(
                    &context.output,
                    &context.db,
                    &context.app_event_tx,
                    &context.id,
                    &message,
                )
                .await;
            }
        }
    }

    /// Requests one immediate reducer-driven git-status refresh.
    pub(super) fn request_git_status_refresh(app_event_tx: &mpsc::UnboundedSender<AppEvent>) {
        // Fire-and-forget: receiver may be dropped during shutdown.
        let _ = app_event_tx.send(AppEvent::RefreshGitStatus);
    }

    /// Loads the project-scoped toggle that controls whether generated session
    /// commit messages include the Agentty coauthor trailer.
    pub(crate) async fn load_include_coauthored_by_agentty_setting(
        db: &Database,
        session_id: &str,
    ) -> bool {
        let Some(project_id) = db.load_session_project_id(session_id).await.ok().flatten() else {
            return true;
        };

        db.get_project_setting(project_id, SettingName::IncludeCoauthoredByAgentty)
            .await
            .ok()
            .flatten()
            .and_then(|setting_value| setting_value.parse::<bool>().ok())
            .unwrap_or(true)
    }

    /// Loads the model used by auto-commit utility prompts for one session.
    ///
    /// This prefers the active project's `DefaultFastModel`, falls back to
    /// `DefaultSmartModel`, and finally returns `fallback_model` when no
    /// persisted setting can be parsed.
    pub(crate) async fn load_auto_commit_model_setting(
        db: &Database,
        session_id: &str,
        fallback_model: AgentModel,
    ) -> AgentModel {
        let project_id = db.load_session_project_id(session_id).await.ok().flatten();

        if let Some(model) =
            Self::load_project_model_setting(db, project_id, SettingName::DefaultFastModel).await
        {
            return model;
        }

        if let Some(model) =
            Self::load_project_model_setting(db, project_id, SettingName::DefaultSmartModel).await
        {
            return model;
        }

        fallback_model
    }

    async fn commit_changes_with_assist(
        context: &AssistContext,
    ) -> Result<Option<SessionCommitOutcome>, SessionError> {
        let mut failure_tracker =
            FailureTracker::new(AUTO_COMMIT_ASSIST_POLICY.max_identical_failure_streak);
        // Test repos do not install hooks deterministically; skip hook
        // execution in tests to keep auto-commit behavior stable.
        let skip_verify_hooks = cfg!(test);

        for assist_attempt in 1..=AUTO_COMMIT_ASSIST_POLICY.max_attempts + 1 {
            match Self::commit_changes_with_git_client(context, skip_verify_hooks).await {
                Ok(commit_outcome) => {
                    return Ok(Some(commit_outcome));
                }
                Err(commit_error) if commit_error.to_string().contains("Nothing to commit") => {
                    return Ok(None);
                }
                Err(commit_error) => {
                    // Keep test execution deterministic and offline by skipping
                    // model-assisted commit retries.
                    if cfg!(test) {
                        return Err(commit_error);
                    }

                    let commit_error_str = commit_error.to_string();
                    if failure_tracker.observe(&commit_error_str) {
                        return Err(SessionError::Workflow(format!(
                            "Auto-commit assistance made no progress: repeated identical commit \
                             failure. Last error: {commit_error_str}"
                        )));
                    }

                    if assist_attempt > AUTO_COMMIT_ASSIST_POLICY.max_attempts {
                        return Err(commit_error);
                    }

                    Self::append_commit_assist_header(context, assist_attempt, &commit_error_str)
                        .await;
                    Self::run_commit_assist_for_error(context, &commit_error_str).await?;
                }
            }
        }

        Err(SessionError::Workflow(
            "Failed to auto-commit after assistance attempts".to_string(),
        ))
    }

    /// Commits all worktree changes and returns the current `HEAD` short hash.
    ///
    /// Pass `no_verify` to skip commit hooks (used in tests for deterministic
    /// execution without pre-commit setup). The model used for commit-message
    /// generation is resolved from the session's auto-commit settings before
    /// the git commit is attempted.
    ///
    /// # Errors
    /// Returns an error if commit-message generation, staging/commit, or
    /// `HEAD` resolution fails.
    async fn commit_changes_with_git_client(
        context: &AssistContext,
        no_verify: bool,
    ) -> Result<SessionCommitOutcome, SessionError> {
        let base_branch = context
            .db
            .get_session_base_branch(&context.id)
            .await?
            .ok_or_else(|| {
                SessionError::Workflow("Missing session base branch for auto-commit".to_string())
            })?;
        let auto_commit_model =
            Self::load_auto_commit_model_setting(&context.db, &context.id, context.session_model)
                .await;

        Self::commit_session_changes(
            context.git_client.as_ref(),
            &context.folder,
            &base_branch,
            auto_commit_model,
            no_verify,
            Self::load_include_coauthored_by_agentty_setting(&context.db, &context.id).await,
        )
        .await
    }

    /// Loads one project-scoped model setting and parses it into an
    /// [`AgentModel`].
    async fn load_project_model_setting(
        db: &Database,
        project_id: Option<i64>,
        setting_name: SettingName,
    ) -> Option<AgentModel> {
        let project_id = project_id?;

        db.get_project_setting(project_id, setting_name)
            .await
            .ok()
            .flatten()
            .and_then(|setting_value| setting_value.parse::<AgentModel>().ok())
    }

    async fn append_commit_assist_header(
        context: &AssistContext,
        assist_attempt: usize,
        commit_error: &str,
    ) {
        let formatted_error = Self::format_commit_error_for_display(commit_error);
        append_assist_header(
            context,
            "Commit",
            assist_attempt,
            AUTO_COMMIT_ASSIST_POLICY.max_attempts,
            "Resolving auto-commit failure:",
            &formatted_error,
        )
        .await;
    }

    async fn run_commit_assist_for_error(
        context: &AssistContext,
        commit_error: &str,
    ) -> Result<(), SessionError> {
        let prompt = Self::auto_commit_assist_prompt(commit_error)?;
        let assist_context = AssistContext {
            app_event_tx: context.app_event_tx.clone(),
            child_pid: Arc::clone(&context.child_pid),
            db: context.db.clone(),
            folder: context.folder.clone(),
            git_client: Arc::clone(&context.git_client),
            id: context.id.clone(),
            output: Arc::clone(&context.output),
            session_model: context.session_model,
        };

        run_agent_assist(&assist_context, &prompt)
            .await
            .map_err(|error| error.with_context("Commit assistance failed"))
    }

    /// Renders the commit-assistance prompt from the markdown template.
    ///
    /// # Errors
    /// Returns an error if Askama template rendering fails.
    fn auto_commit_assist_prompt(commit_error: &str) -> Result<String, SessionError> {
        let commit_error = commit_error.trim();
        let template = AutoCommitAssistPromptTemplate { commit_error };

        template.render().map_err(|error| {
            SessionError::Workflow(format!(
                "Failed to render `auto_commit_assist_prompt.md`: {error}"
            ))
        })
    }

    fn format_commit_error_for_display(commit_error: &str) -> String {
        format_detail_lines(commit_error)
    }

    /// Renders the commit-message generation prompt from the markdown
    /// template.
    ///
    /// # Errors
    /// Returns an error if Askama template rendering fails.
    fn session_commit_message_prompt(
        diff: &str,
        current_commit_message: Option<&str>,
    ) -> Result<String, SessionError> {
        let stripped_current_commit_message =
            current_commit_message.map_or_else(String::new, strip_agentty_coauthor_trailer);
        let template = SessionCommitMessagePromptTemplate {
            current_commit_message: stripped_current_commit_message.trim(),
            diff,
        };

        template.render().map_err(|error| {
            SessionError::Workflow(format!(
                "Failed to render `session_commit_message_prompt.md`: {error}"
            ))
        })
    }

    /// Generates the canonical session commit message, commits the current
    /// worktree state, and returns the rewritten `HEAD` details.
    ///
    /// # Errors
    /// Returns an error if the worktree is clean, the cumulative session diff
    /// cannot be generated, commit-message generation fails, or the git commit
    /// cannot be created/amended.
    pub(crate) async fn commit_session_changes(
        git_client: &dyn GitClient,
        folder: &Path,
        base_branch: &str,
        session_model: AgentModel,
        no_verify: bool,
        include_coauthored_by_agentty: bool,
    ) -> Result<SessionCommitOutcome, SessionError> {
        if cfg!(test) {
            let folder = folder.to_path_buf();
            if git_client.is_worktree_clean(folder.clone()).await? {
                return Err(SessionError::Workflow(
                    "Nothing to commit: no changes detected".to_string(),
                ));
            }

            let has_session_commit = git_client
                .has_commits_since(folder.clone(), base_branch.to_string())
                .await?;
            let current_commit_message = if has_session_commit {
                git_client.head_commit_message(folder.clone()).await?
            } else {
                None
            };
            let Some(current_commit_message) = current_commit_message.as_deref().map(str::trim)
            else {
                return Err(SessionError::Workflow(
                    "Session commit generation requires an existing commit message during tests"
                        .to_string(),
                ));
            };
            if current_commit_message.is_empty() {
                return Err(SessionError::Workflow(
                    "Session commit generation requires a non-blank existing commit message \
                     during tests"
                        .to_string(),
                ));
            }
            let commit_message = append_agentty_coauthor_trailer(
                strip_agentty_coauthor_trailer(current_commit_message).trim(),
                include_coauthored_by_agentty,
            );
            git_client
                .commit_all_preserving_single_commit(
                    folder.clone(),
                    base_branch.to_string(),
                    commit_message.clone(),
                    git::SingleCommitMessageStrategy::Replace,
                    no_verify,
                )
                .await?;
            let commit_hash = git_client.head_short_hash(folder).await?;

            return Ok(SessionCommitOutcome {
                commit_hash,
                commit_message,
            });
        }

        let backend = agent::create_backend(session_model.kind());

        Self::commit_session_changes_with_backend(
            git_client,
            folder,
            base_branch,
            session_model,
            backend.as_ref(),
            no_verify,
            include_coauthored_by_agentty,
        )
        .await
    }

    /// Testable variant of [`SessionTaskService::commit_session_changes`] that
    /// accepts an injected backend for deterministic prompt generation.
    ///
    /// # Errors
    /// Returns an error if the worktree is clean, the cumulative session diff
    /// cannot be generated, commit-message generation fails, or the git commit
    /// cannot be created/amended.
    async fn commit_session_changes_with_backend(
        git_client: &dyn GitClient,
        folder: &Path,
        base_branch: &str,
        session_model: AgentModel,
        backend: &dyn agent::AgentBackend,
        no_verify: bool,
        include_coauthored_by_agentty: bool,
    ) -> Result<SessionCommitOutcome, SessionError> {
        let folder = folder.to_path_buf();
        if git_client.is_worktree_clean(folder.clone()).await? {
            return Err(SessionError::Workflow(
                "Nothing to commit: no changes detected".to_string(),
            ));
        }

        let diff = git_client
            .diff(folder.clone(), base_branch.to_string())
            .await?;
        let has_session_commit = git_client
            .has_commits_since(folder.clone(), base_branch.to_string())
            .await?;
        let current_commit_message = if has_session_commit {
            git_client.head_commit_message(folder.clone()).await?
        } else {
            None
        };
        let generated_commit_message = Self::generate_session_commit_message_with_backend(
            folder.as_path(),
            session_model,
            diff.as_str(),
            current_commit_message.as_deref(),
            backend,
            include_coauthored_by_agentty,
        )
        .await?;

        git_client
            .commit_all_preserving_single_commit(
                folder.clone(),
                base_branch.to_string(),
                generated_commit_message.clone(),
                git::SingleCommitMessageStrategy::Replace,
                no_verify,
            )
            .await?;

        let commit_hash = git_client.head_short_hash(folder).await?;

        Ok(SessionCommitOutcome {
            commit_hash,
            commit_message: generated_commit_message,
        })
    }

    /// Renders the session commit-message prompt, submits it to the injected
    /// backend, validates the returned text, and appends the optional
    /// coauthor trailer in code.
    ///
    /// # Errors
    /// Returns an error when prompt rendering fails, the one-shot agent call
    /// fails, or the returned `answer` text is blank.
    async fn generate_session_commit_message_with_backend(
        folder: &Path,
        session_model: AgentModel,
        diff: &str,
        current_commit_message: Option<&str>,
        backend: &dyn agent::AgentBackend,
        include_coauthored_by_agentty: bool,
    ) -> Result<String, SessionError> {
        let prompt = Self::session_commit_message_prompt(diff, current_commit_message)?;
        let submission = Self::submit_utility_prompt_with_backend(
            session_model,
            backend,
            agent::OneShotRequest {
                child_pid: None,
                folder,
                model: session_model,
                prompt: &prompt,
                request_kind: crate::infra::channel::AgentRequestKind::UtilityPrompt,
                reasoning_level: crate::domain::agent::ReasoningLevel::default(),
            },
        )
        .await?;
        let answer_text = submission.response.to_answer_display_text();
        let trimmed_answer_text = answer_text.trim();
        if trimmed_answer_text.is_empty() {
            return Err(SessionError::Workflow(
                "Session commit message model returned blank answer text".to_string(),
            ));
        }
        validate_generated_commit_message(trimmed_answer_text)?;

        Ok(append_agentty_coauthor_trailer(
            trimmed_answer_text,
            include_coauthored_by_agentty,
        ))
    }

    /// Executes one isolated assist prompt and appends the normalized answer
    /// text to the session transcript.
    ///
    /// # Errors
    /// Returns an error when the one-shot prompt fails or returns invalid
    /// protocol output.
    pub(crate) async fn run_agent_assist_task(
        input: RunAgentAssistTaskInput,
    ) -> Result<(), SessionError> {
        let backend = agent::create_backend(input.session_model.kind());

        Self::run_agent_assist_task_with_backend(input, backend.as_ref()).await
    }

    /// Executes one isolated assist prompt using the provided backend.
    ///
    /// # Errors
    /// Returns an error when the one-shot prompt fails or returns invalid
    /// protocol output.
    async fn run_agent_assist_task_with_backend(
        input: RunAgentAssistTaskInput,
        backend: &dyn agent::AgentBackend,
    ) -> Result<(), SessionError> {
        let RunAgentAssistTaskInput {
            app_event_tx,
            child_pid,
            db,
            folder,
            id,
            output,
            prompt,
            session_model,
        } = input;
        let assist_submission = Self::submit_utility_prompt_with_backend(
            session_model,
            backend,
            agent::OneShotRequest {
                child_pid: Some(child_pid.as_ref()),
                folder: &folder,
                model: session_model,
                prompt: &prompt,
                request_kind: crate::infra::channel::AgentRequestKind::UtilityPrompt,
                reasoning_level: crate::domain::agent::ReasoningLevel::default(),
            },
        )
        .await?;

        let answer_text = assist_submission.response.to_answer_display_text();
        if !answer_text.trim().is_empty() {
            Self::append_session_output(&output, &db, &app_event_tx, &id, &answer_text).await;
        }

        // Best-effort: stats persistence failure is non-critical.
        let _ = db.update_session_stats(&id, &assist_submission.stats).await;
        // Best-effort: usage persistence failure is non-critical.
        let _ = db
            .upsert_session_usage(&id, session_model.as_str(), &assist_submission.stats)
            .await;

        Ok(())
    }

    /// Executes one isolated utility prompt, routing app-server-backed models
    /// through the shared app-server client while preserving backend injection
    /// for direct CLI providers in tests and production.
    ///
    /// # Errors
    /// Returns an error when the one-shot prompt fails or the response does
    /// not satisfy the structured protocol schema.
    async fn submit_utility_prompt_with_backend(
        session_model: AgentModel,
        backend: &dyn agent::AgentBackend,
        request: agent::OneShotRequest<'_>,
    ) -> Result<agent::OneShotSubmission, SessionError> {
        if agent::transport_mode(session_model.kind()).uses_app_server() {
            let app_server_client = agent::create_app_server_client(session_model.kind(), None)
                .ok_or_else(|| {
                    SessionError::Workflow(format!(
                        "{} provider did not provide an app-server client",
                        session_model.kind()
                    ))
                })?;

            return agent::submit_one_shot_with_app_server_client(
                app_server_client.as_ref(),
                request,
            )
            .await
            .map_err(SessionError::Workflow);
        }

        agent::submit_one_shot_with_backend(backend, request)
            .await
            .map_err(SessionError::Workflow)
    }

    /// Applies a status transition to memory and database when valid.
    ///
    /// This emits [`AppEvent::SessionUpdated`] for targeted snapshot sync and
    /// emits [`AppEvent::RefreshSessions`] for transitions that require full
    /// list reload.
    pub(crate) async fn update_status(
        status: &Mutex<Status>,
        clock: &dyn Clock,
        db: &Database,
        app_event_tx: &mpsc::UnboundedSender<AppEvent>,
        id: &str,
        new: Status,
    ) -> bool {
        let should_update = if let Ok(mut current) = status.lock() {
            if (*current).can_transition_to(new) {
                *current = new;
                true
            } else {
                false
            }
        } else {
            false
        };
        if !should_update {
            return false;
        }

        let timestamp_seconds = unix_timestamp_from_system_time(clock.now_system_time());

        // Best-effort: status persistence failure is non-critical.
        let _ = db
            .update_session_status_with_timing_at(id, &new.to_string(), timestamp_seconds)
            .await;
        let session_id = id.to_string();
        // Fire-and-forget: receiver may be dropped during shutdown.
        let _ = app_event_tx.send(AppEvent::SessionUpdated { session_id });
        if Self::status_requires_full_refresh(new) {
            // Fire-and-forget: receiver may be dropped during shutdown.
            let _ = app_event_tx.send(AppEvent::RefreshSessions);
        }

        true
    }

    /// Appends output to the in-memory handle buffer and database.
    pub(crate) async fn append_session_output(
        output: &Arc<Mutex<String>>,
        db: &Database,
        app_event_tx: &mpsc::UnboundedSender<AppEvent>,
        id: &str,
        message: &str,
    ) {
        if let Ok(mut buf) = output.lock() {
            buf.push_str(message);
        }
        // Best-effort: output persistence failure is non-critical.
        let _ = db.append_session_output(id, message).await;
        // Fire-and-forget: receiver may be dropped during shutdown.
        let _ = app_event_tx.send(AppEvent::SessionUpdated {
            session_id: id.to_string(),
        });
    }

    /// Clears the transient thinking message for one session.
    pub(crate) fn clear_session_progress(app_event_tx: &mpsc::UnboundedSender<AppEvent>, id: &str) {
        Self::set_session_progress(app_event_tx, id, None);
    }

    /// Emits a transient thinking message update for one session.
    pub(crate) fn set_session_progress(
        app_event_tx: &mpsc::UnboundedSender<AppEvent>,
        id: &str,
        progress_message: Option<String>,
    ) {
        // Fire-and-forget: receiver may be dropped during shutdown.
        let _ = app_event_tx.send(AppEvent::SessionProgressUpdated {
            progress_message,
            session_id: id.to_string(),
        });
    }

    fn status_requires_full_refresh(status: Status) -> bool {
        matches!(
            status,
            Status::InProgress | Status::Review | Status::Merging | Status::Done | Status::Canceled
        )
    }
}

/// Removes the Agentty coauthor trailer from one commit message so prompt
/// continuity and test-mode reuse operate on body/title content only.
fn strip_agentty_coauthor_trailer(commit_message: &str) -> String {
    commit_message
        .lines()
        .filter(|line| line.trim() != SESSION_COMMIT_COAUTHORED_BY_AGENTTY_TRAILER)
        .collect::<Vec<_>>()
        .join("\n")
}

/// Validates generated commit-message output before git commit creation.
///
/// # Errors
/// Returns an error when the generated message already contains the Agentty
/// coauthor trailer, which is appended by code instead of model output.
fn validate_generated_commit_message(commit_message: &str) -> Result<(), SessionError> {
    if commit_message
        .lines()
        .any(|line| line.trim() == SESSION_COMMIT_COAUTHORED_BY_AGENTTY_TRAILER)
    {
        return Err(SessionError::Workflow(
            "Session commit message model must not emit the Agentty coauthor trailer".to_string(),
        ));
    }

    Ok(())
}

/// Appends the Agentty coauthor trailer when the project setting enables it.
fn append_agentty_coauthor_trailer(
    commit_message: &str,
    include_coauthored_by_agentty: bool,
) -> String {
    let trimmed_commit_message = commit_message.trim().to_string();

    if !include_coauthored_by_agentty || trimmed_commit_message.is_empty() {
        return trimmed_commit_message;
    }

    format!("{trimmed_commit_message}\n\n{SESSION_COMMIT_COAUTHORED_BY_AGENTTY_TRAILER}")
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;
    use std::process::Command;
    use std::sync::Mutex as StdMutex;
    use std::time::{Duration, Instant, SystemTime};

    use super::*;
    use crate::db::Database;
    use crate::infra::agent::tests::MockAgentBackend;
    use crate::infra::channel::AgentRequestKind;
    use crate::infra::git::{GitError, MockGitClient};

    /// Mutable test clock used to drive deterministic status-transition timing
    /// assertions.
    struct StaticClock {
        now_system_time: StdMutex<SystemTime>,
    }

    impl StaticClock {
        /// Creates a test clock seeded with one wall-clock timestamp.
        fn new(now_system_time: SystemTime) -> Self {
            Self {
                now_system_time: StdMutex::new(now_system_time),
            }
        }

        /// Replaces the current wall-clock timestamp returned by the clock.
        fn set_now_system_time(&self, now_system_time: SystemTime) {
            *self
                .now_system_time
                .lock()
                .expect("static clock lock should not be poisoned") = now_system_time;
        }
    }

    impl Clock for StaticClock {
        fn now_instant(&self) -> Instant {
            Instant::now()
        }

        fn now_system_time(&self) -> SystemTime {
            *self
                .now_system_time
                .lock()
                .expect("static clock lock should not be poisoned")
        }
    }

    /// Builds one deterministic shell command used by mocked backends.
    fn mock_shell_command(stdout: &str, stderr: &str, exit_code: i32) -> Command {
        let mut command = Command::new("sh");
        command.arg("-c").arg(
            "printf '%s' \"$ASSIST_STDOUT\"; printf '%s' \"$ASSIST_STDERR\" >&2; exit \
             \"$ASSIST_EXIT\"",
        );
        command.env("ASSIST_STDOUT", stdout);
        command.env("ASSIST_STDERR", stderr);
        command.env("ASSIST_EXIT", exit_code.to_string());
        command.stdout(std::process::Stdio::piped());
        command.stderr(std::process::Stdio::piped());

        command
    }

    /// Inserts one review session used by assist-task tests.
    async fn insert_review_session(database: &Database, model: &str) {
        let project_id = database
            .upsert_project("/tmp/project", Some("main"))
            .await
            .expect("failed to upsert project");
        database
            .insert_session("session-id", model, "main", "Review", project_id)
            .await
            .expect("failed to insert session");
    }

    #[test]
    /// Verifies lifecycle statuses that require full list refreshes are
    /// enumerated correctly.
    fn test_status_requires_full_refresh_for_lifecycle_statuses() {
        // Arrange
        let refresh_statuses = [
            Status::InProgress,
            Status::Review,
            Status::Merging,
            Status::Done,
            Status::Canceled,
        ];

        // Act & Assert
        for status in refresh_statuses {
            assert!(SessionTaskService::status_requires_full_refresh(status));
        }
        assert!(!SessionTaskService::status_requires_full_refresh(
            Status::New
        ));
    }

    #[tokio::test]
    async fn test_update_status_accumulates_repeated_in_progress_intervals() {
        // Arrange
        let database = Database::open_in_memory()
            .await
            .expect("failed to open in-memory db");
        let project_id = database
            .upsert_project("/tmp/project", Some("main"))
            .await
            .expect("failed to upsert project");
        database
            .insert_session(
                "session-id",
                "gpt-5.4",
                "main",
                &Status::New.to_string(),
                project_id,
            )
            .await
            .expect("failed to insert session");
        let status = Mutex::new(Status::New);
        let clock = StaticClock::new(SystemTime::UNIX_EPOCH + Duration::from_secs(10));
        let (app_event_tx, _app_event_rx) = mpsc::unbounded_channel();

        // Act
        let entered_first_interval = SessionTaskService::update_status(
            &status,
            &clock,
            &database,
            &app_event_tx,
            "session-id",
            Status::InProgress,
        )
        .await;
        clock.set_now_system_time(SystemTime::UNIX_EPOCH + Duration::from_secs(70));
        let left_first_interval = SessionTaskService::update_status(
            &status,
            &clock,
            &database,
            &app_event_tx,
            "session-id",
            Status::Review,
        )
        .await;
        clock.set_now_system_time(SystemTime::UNIX_EPOCH + Duration::from_secs(100));
        let entered_second_interval = SessionTaskService::update_status(
            &status,
            &clock,
            &database,
            &app_event_tx,
            "session-id",
            Status::InProgress,
        )
        .await;
        clock.set_now_system_time(SystemTime::UNIX_EPOCH + Duration::from_secs(190));
        let left_second_interval = SessionTaskService::update_status(
            &status,
            &clock,
            &database,
            &app_event_tx,
            "session-id",
            Status::Question,
        )
        .await;
        let session_row = database
            .load_sessions()
            .await
            .expect("failed to load sessions")
            .into_iter()
            .find(|row| row.id == "session-id")
            .expect("missing session row");

        // Assert
        assert!(entered_first_interval);
        assert!(left_first_interval);
        assert!(entered_second_interval);
        assert!(left_second_interval);
        assert_eq!(session_row.status, "Question");
        assert_eq!(session_row.in_progress_started_at, None);
        assert_eq!(session_row.in_progress_total_seconds, 150);
    }

    #[test]
    /// Ensures commit assistance prompts include the raw git failure details.
    fn test_auto_commit_assist_prompt_includes_commit_error() {
        // Arrange
        let commit_error = "Failed to commit: merge conflict remains";

        // Act
        let prompt = SessionTaskService::auto_commit_assist_prompt(commit_error)
            .expect("auto commit assist prompt should render");

        // Assert
        assert!(prompt.contains("Failed to commit: merge conflict remains"));
        assert!(prompt.contains("return the required protocol JSON object"));
        assert!(prompt.contains("`answer` field only"));
    }

    #[test]
    /// Ensures commit error formatting normalizes output as bullet lines.
    fn test_format_commit_error_for_display_returns_bulleted_lines() {
        // Arrange
        let commit_error = "line one\nline two";

        // Act
        let formatted = SessionTaskService::format_commit_error_for_display(commit_error);

        // Assert
        assert_eq!(formatted, "- line one\n- line two");
    }

    #[test]
    /// Verifies session commit-message prompts include both the continuity
    /// input and the cumulative diff.
    fn test_session_commit_message_prompt_includes_continuity_and_diff() {
        // Arrange
        let diff = "diff --git a/a.rs b/a.rs";
        let current_commit_message = Some("Keep session commit accurate");

        // Act
        let prompt =
            SessionTaskService::session_commit_message_prompt(diff, current_commit_message)
                .expect("prompt should render");

        // Assert
        assert!(prompt.contains("Keep session commit accurate"));
        assert!(prompt.contains(diff));
        assert!(prompt.contains("required protocol JSON object"));
        assert!(!prompt.contains("Return one plain-text commit message"));
        assert!(!prompt.contains(SESSION_COMMIT_COAUTHORED_BY_AGENTTY_TRAILER));
    }

    #[test]
    /// Verifies prompt rendering strips the Agentty trailer from existing
    /// commit-message continuity before sending it back to the model.
    fn test_session_commit_message_prompt_strips_coauthor_trailer_from_continuity() {
        // Arrange
        let diff = "diff --git a/a.rs b/a.rs";
        let current_commit_message = format!(
            "Keep session commit accurate\n\n{SESSION_COMMIT_COAUTHORED_BY_AGENTTY_TRAILER}"
        );

        // Act
        let prompt = SessionTaskService::session_commit_message_prompt(
            diff,
            Some(current_commit_message.as_str()),
        )
        .expect("prompt should render");

        // Assert
        assert!(!prompt.contains(SESSION_COMMIT_COAUTHORED_BY_AGENTTY_TRAILER));
        assert!(prompt.contains("Keep session commit accurate"));
    }

    #[tokio::test]
    /// Verifies plain-text one-shot output is rejected for session commit
    /// message generation after both the original parse and the
    /// protocol-repair retry fail.
    async fn test_generate_session_commit_message_with_backend_rejects_plain_text_output() {
        // Arrange — use a CLI-backed model so the mock backend is exercised.
        // App-server-backed models (Codex, Gemini) bypass `build_command`
        // entirely and route through the shared app-server client.
        let temp_directory = tempfile::tempdir().expect("failed to create temp dir");
        let mut backend = MockAgentBackend::new();
        backend
            .expect_build_command()
            .times(2)
            .returning(|request| {
                assert!(matches!(
                    request.request_kind,
                    AgentRequestKind::UtilityPrompt
                ));

                Ok(mock_shell_command(
                    "Refactor agent prompt and protocol handling",
                    "",
                    0,
                ))
            });

        // Act
        let error = SessionTaskService::generate_session_commit_message_with_backend(
            temp_directory.path(),
            AgentModel::ClaudeSonnet46,
            "diff --git a/a.rs b/a.rs",
            None,
            &backend,
            false,
        )
        .await
        .expect_err("plain-text one-shot commit message should fail");

        // Assert
        assert!(
            error
                .to_string()
                .contains("did not match the required JSON schema")
        );
        assert!(
            error
                .to_string()
                .contains("response:\nRefactor agent prompt and protocol handling")
        );
    }

    #[test]
    /// Verifies append-only handling adds the coauthor trailer once
    /// when the setting is enabled.
    fn test_append_agentty_coauthor_trailer_appends_trailer_once() {
        // Arrange
        let commit_message = "Refine settings page";

        // Act
        let appended_commit_message = append_agentty_coauthor_trailer(commit_message, true);

        // Assert
        assert_eq!(
            appended_commit_message,
            format!("Refine settings page\n\n{SESSION_COMMIT_COAUTHORED_BY_AGENTTY_TRAILER}")
        );
    }

    #[test]
    /// Verifies append-only handling leaves the generated message unchanged
    /// when the setting is disabled.
    fn test_append_agentty_coauthor_trailer_leaves_message_unchanged_when_disabled() {
        // Arrange
        let commit_message = "Refine settings page";

        // Act
        let appended_commit_message = append_agentty_coauthor_trailer(commit_message, false);

        // Assert
        assert_eq!(appended_commit_message, "Refine settings page");
    }

    #[test]
    /// Verifies generated commit-message validation rejects model output that
    /// already includes the Agentty trailer.
    fn test_validate_generated_commit_message_rejects_agentty_trailer() {
        // Arrange
        let commit_message =
            format!("Refine settings page\n\n{SESSION_COMMIT_COAUTHORED_BY_AGENTTY_TRAILER}");

        // Act
        let error = validate_generated_commit_message(&commit_message)
            .expect_err("generated trailer should fail validation");

        // Assert
        assert_eq!(
            error.to_string(),
            "Session commit message model must not emit the Agentty coauthor trailer"
        );
    }

    #[test]
    /// Verifies trailer stripping removes the Agentty trailer from reused
    /// commit-message continuity.
    fn test_strip_agentty_coauthor_trailer_removes_trailer_line() {
        // Arrange
        let commit_message =
            format!("Refine settings page\n\n{SESSION_COMMIT_COAUTHORED_BY_AGENTTY_TRAILER}");

        // Act
        let stripped_commit_message = strip_agentty_coauthor_trailer(&commit_message);

        // Assert
        assert_eq!(stripped_commit_message, "Refine settings page\n");
    }

    #[tokio::test]
    /// Verifies commit helper failure appends a commit error message without
    /// invoking real git or agent subprocesses.
    async fn test_handle_auto_commit_appends_commit_error_from_mock_git_client() {
        // Arrange
        let mut mock_git_client = MockGitClient::new();
        mock_git_client
            .expect_is_worktree_clean()
            .times(1)
            .returning(|_| {
                Box::pin(async { Err(GitError::OutputParse("commit failed".to_string())) })
            });
        let database = Database::open_in_memory()
            .await
            .expect("failed to open in-memory db");
        insert_review_session(&database, AgentModel::Gpt54.as_str()).await;
        let (app_event_tx, _app_event_rx) = mpsc::unbounded_channel();
        let output = Arc::new(Mutex::new(String::new()));
        let context = AssistContext {
            app_event_tx,
            child_pid: Arc::new(Mutex::new(None)),
            db: database,
            folder: PathBuf::from("/tmp/project"),
            git_client: Arc::new(mock_git_client),
            id: "session-id".to_string(),
            output: Arc::clone(&output),
            session_model: AgentModel::Gpt54,
        };

        // Act
        SessionTaskService::handle_auto_commit(context).await;

        // Assert
        let output_text = output
            .lock()
            .map(|buffer| buffer.clone())
            .unwrap_or_default();
        assert!(output_text.contains("[Commit Error] commit failed"));
    }

    #[tokio::test]
    /// Verifies auto-commit reports clean-worktree no-op commits in the
    /// session output.
    async fn test_handle_auto_commit_reports_when_no_changes_exist() {
        // Arrange
        let mut mock_git_client = MockGitClient::new();
        mock_git_client
            .expect_is_worktree_clean()
            .times(1)
            .returning(|_| Box::pin(async { Ok::<_, GitError>(true) }));
        let database = Database::open_in_memory()
            .await
            .expect("failed to open in-memory db");
        insert_review_session(&database, AgentModel::Gpt54.as_str()).await;
        let (app_event_tx, _app_event_rx) = mpsc::unbounded_channel();
        let output = Arc::new(Mutex::new(String::new()));
        let context = AssistContext {
            app_event_tx,
            child_pid: Arc::new(Mutex::new(None)),
            db: database,
            folder: PathBuf::from("/tmp/project"),
            git_client: Arc::new(mock_git_client),
            id: "session-id".to_string(),
            output: Arc::clone(&output),
            session_model: AgentModel::Gpt54,
        };

        // Act
        SessionTaskService::handle_auto_commit(context).await;

        // Assert
        let output_text = output
            .lock()
            .map(|buffer| buffer.clone())
            .unwrap_or_default();
        assert!(output_text.contains("[Commit] No changes to commit."));
    }

    #[tokio::test]
    /// Verifies successful auto-commit updates the title while preserving the
    /// persisted agent session summary text.
    async fn test_handle_auto_commit_preserves_agent_session_summary() {
        // Arrange
        let mut mock_git_client = MockGitClient::new();
        mock_git_client
            .expect_is_worktree_clean()
            .times(1)
            .returning(|_| Box::pin(async { Ok::<_, GitError>(false) }));
        mock_git_client
            .expect_has_commits_since()
            .times(1)
            .returning(|_, _| Box::pin(async { Ok::<_, GitError>(true) }));
        mock_git_client
            .expect_head_commit_message()
            .times(1)
            .returning(|_| {
                Box::pin(async {
                    Ok::<_, GitError>(Some(
                        "Refine README updates\n\n- Keep title aligned with commit".to_string(),
                    ))
                })
            });
        mock_git_client
            .expect_commit_all_preserving_single_commit()
            .times(1)
            .returning(|_, _, _, _, _| Box::pin(async { Ok::<_, GitError>(()) }));
        mock_git_client
            .expect_head_short_hash()
            .times(1)
            .returning(|_| Box::pin(async { Ok::<_, GitError>("abc1234".to_string()) }));
        let database = Database::open_in_memory()
            .await
            .expect("failed to open in-memory db");
        insert_review_session(&database, AgentModel::Gpt54.as_str()).await;
        let summary_payload = "- Session branch updates README formatting.".to_string();
        database
            .update_session_summary("session-id", &summary_payload)
            .await
            .expect("failed to persist summary text");
        let (app_event_tx, mut app_event_rx) = mpsc::unbounded_channel();
        let output = Arc::new(Mutex::new(String::new()));
        let context = AssistContext {
            app_event_tx,
            child_pid: Arc::new(Mutex::new(None)),
            db: database.clone(),
            folder: PathBuf::from("/tmp/project"),
            git_client: Arc::new(mock_git_client),
            id: "session-id".to_string(),
            output: Arc::clone(&output),
            session_model: AgentModel::Gpt54,
        };

        // Act
        SessionTaskService::handle_auto_commit(context).await;
        let sessions = database
            .load_sessions()
            .await
            .expect("failed to load sessions");

        // Assert
        assert_eq!(sessions[0].title.as_deref(), Some("Refine README updates"));
        assert_eq!(
            sessions[0].summary.as_deref(),
            Some("- Session branch updates README formatting.")
        );
        let output_text = output
            .lock()
            .map(|buffer| buffer.clone())
            .unwrap_or_default();
        assert!(output_text.contains("[Commit] committed with hash `abc1234`"));
        let events = std::iter::from_fn(|| app_event_rx.try_recv().ok()).collect::<Vec<_>>();
        assert!(events.contains(&AppEvent::RefreshGitStatus));
    }

    #[tokio::test]
    /// Verifies auto-commit prefers the project fast model before other
    /// fallback settings.
    async fn test_load_auto_commit_model_setting_prefers_project_fast_model() {
        // Arrange
        let database = Database::open_in_memory()
            .await
            .expect("failed to open in-memory db");
        insert_review_session(&database, AgentModel::Gpt54.as_str()).await;
        let project_id = database
            .load_session_project_id("session-id")
            .await
            .expect("failed to load session project id")
            .expect("session should have project id");
        database
            .upsert_project_setting(
                project_id,
                SettingName::DefaultFastModel,
                AgentModel::ClaudeHaiku4520251001.as_str(),
            )
            .await
            .expect("failed to persist default fast model");
        database
            .upsert_project_setting(
                project_id,
                SettingName::DefaultSmartModel,
                AgentModel::Gemini31ProPreview.as_str(),
            )
            .await
            .expect("failed to persist default smart model");

        // Act
        let auto_commit_model = SessionTaskService::load_auto_commit_model_setting(
            &database,
            "session-id",
            AgentModel::Gpt54,
        )
        .await;

        // Assert
        assert_eq!(auto_commit_model, AgentModel::ClaudeHaiku4520251001);
    }

    #[tokio::test]
    /// Verifies auto-commit falls back through smart and session defaults
    /// when the fast-model setting is absent.
    async fn test_load_auto_commit_model_setting_falls_back_through_defaults() {
        // Arrange
        let database = Database::open_in_memory()
            .await
            .expect("failed to open in-memory db");
        insert_review_session(&database, AgentModel::Gpt54.as_str()).await;
        let project_id = database
            .load_session_project_id("session-id")
            .await
            .expect("failed to load session project id")
            .expect("session should have project id");
        database
            .upsert_project_setting(
                project_id,
                SettingName::DefaultSmartModel,
                AgentModel::Gemini31ProPreview.as_str(),
            )
            .await
            .expect("failed to persist default smart model");

        // Act
        let smart_fallback_model = SessionTaskService::load_auto_commit_model_setting(
            &database,
            "session-id",
            AgentModel::Gpt54,
        )
        .await;

        // Assert
        assert_eq!(smart_fallback_model, AgentModel::Gemini31ProPreview);

        // Arrange
        database
            .upsert_project_setting(project_id, SettingName::DefaultSmartModel, "invalid")
            .await
            .expect("failed to persist invalid smart model");

        // Act
        let session_fallback_model = SessionTaskService::load_auto_commit_model_setting(
            &database,
            "session-id",
            AgentModel::Gpt54,
        )
        .await;

        // Assert
        assert_eq!(session_fallback_model, AgentModel::Gpt54);
    }

    #[tokio::test]
    /// Verifies one-shot assist output unwraps structured protocol answers
    /// before persistence and session usage updates.
    async fn test_run_agent_assist_task_unwraps_one_shot_answer_without_raw_json() {
        // Arrange
        let database = Database::open_in_memory()
            .await
            .expect("failed to open in-memory db");
        insert_review_session(&database, AgentModel::ClaudeOpus46.as_str()).await;
        let (app_event_tx, _app_event_rx) = mpsc::unbounded_channel();
        let output = Arc::new(Mutex::new(String::new()));
        let child_pid = Arc::new(Mutex::new(None));
        let temp_dir = tempfile::tempdir().expect("failed to create temp dir");
        let mut backend = MockAgentBackend::new();
        backend.expect_build_command().times(1).returning(|request| {
            assert!(matches!(
                request.request_kind,
                AgentRequestKind::UtilityPrompt
            ));
            assert_eq!(request.prompt, "Resolve conflict");

            Ok(mock_shell_command(
                r#"{"result":"{\"answer\":\"Resolved the rebase conflict.\",\"questions\":[],\"summary\":null}","usage":{"input_tokens":11,"output_tokens":7}}"#,
                "",
                0,
            ))
        });

        // Act
        let result = SessionTaskService::run_agent_assist_task_with_backend(
            RunAgentAssistTaskInput {
                app_event_tx,
                child_pid: Arc::clone(&child_pid),
                db: database.clone(),
                folder: temp_dir.path().to_path_buf(),
                id: "session-id".to_string(),
                output: Arc::clone(&output),
                prompt: "Resolve conflict".to_string(),
                session_model: AgentModel::ClaudeOpus46,
            },
            &backend,
        )
        .await;

        // Assert
        assert!(
            result.is_ok(),
            "assist task should succeed: {:?}",
            result.err()
        );
        let output_text = output.lock().map(|buf| buf.clone()).unwrap_or_default();
        assert!(output_text.contains("Resolved the rebase conflict."));
        assert!(!output_text.contains(r#"{"answer""#));
        assert_eq!(*child_pid.lock().expect("failed to lock child pid"), None);
        let sessions = database
            .load_sessions()
            .await
            .expect("failed to load sessions");
        assert_eq!(sessions[0].input_tokens, 11);
        assert_eq!(sessions[0].output_tokens, 7);
    }

    #[tokio::test]
    /// Verifies assist tasks reject plain-text one-shot output after both the
    /// original parse and the protocol-repair retry fail.
    async fn test_run_agent_assist_task_rejects_plain_text_output() {
        // Arrange
        let database = Database::open_in_memory()
            .await
            .expect("failed to open in-memory db");
        insert_review_session(&database, AgentModel::ClaudeOpus46.as_str()).await;
        let (app_event_tx, _app_event_rx) = mpsc::unbounded_channel();
        let output = Arc::new(Mutex::new(String::new()));
        let temp_dir = tempfile::tempdir().expect("failed to create temp dir");
        let mut backend = MockAgentBackend::new();
        backend
            .expect_build_command()
            .times(2)
            .returning(|request| {
                assert!(matches!(
                    request.request_kind,
                    AgentRequestKind::UtilityPrompt
                ));

                Ok(mock_shell_command(
                    r#"{"result":"plain text","usage":{"input_tokens":2,"output_tokens":1}}"#,
                    "",
                    0,
                ))
            });

        // Act
        let error = SessionTaskService::run_agent_assist_task_with_backend(
            RunAgentAssistTaskInput {
                app_event_tx,
                child_pid: Arc::new(Mutex::new(None)),
                db: database.clone(),
                folder: temp_dir.path().to_path_buf(),
                id: "session-id".to_string(),
                output: Arc::clone(&output),
                prompt: "Resolve conflict".to_string(),
                session_model: AgentModel::ClaudeOpus46,
            },
            &backend,
        )
        .await
        .expect_err("plain-text utility output should fail");

        // Assert
        assert!(
            error
                .to_string()
                .contains("did not match the required JSON schema")
        );
        assert!(error.to_string().contains("response:\nplain text"));
        let output_text = output.lock().map(|buf| buf.clone()).unwrap_or_default();
        assert!(output_text.is_empty());
        let sessions = database
            .load_sessions()
            .await
            .expect("failed to load sessions");
        assert_eq!(sessions[0].input_tokens, 0);
        assert_eq!(sessions[0].output_tokens, 0);
    }

    #[tokio::test]
    /// Verifies non-zero assist subprocess exits surface the one-shot command
    /// error details.
    async fn test_run_agent_assist_task_returns_error_for_non_zero_exit_status() {
        // Arrange
        let database = Database::open_in_memory()
            .await
            .expect("failed to open in-memory db");
        insert_review_session(&database, AgentModel::ClaudeOpus46.as_str()).await;
        let (app_event_tx, _app_event_rx) = mpsc::unbounded_channel();
        let temp_dir = tempfile::tempdir().expect("failed to create temp dir");
        let mut backend = MockAgentBackend::new();
        backend
            .expect_build_command()
            .times(1)
            .returning(|_| Ok(mock_shell_command("", "assist failed", 7)));

        // Act
        let result = SessionTaskService::run_agent_assist_task_with_backend(
            RunAgentAssistTaskInput {
                app_event_tx,
                child_pid: Arc::new(Mutex::new(None)),
                db: database,
                folder: temp_dir.path().to_path_buf(),
                id: "session-id".to_string(),
                output: Arc::new(Mutex::new(String::new())),
                prompt: "Resolve conflict".to_string(),
                session_model: AgentModel::ClaudeOpus46,
            },
            &backend,
        )
        .await;

        // Assert
        assert!(result.is_err());
        let error_text = result.expect_err("expected non-zero exit to fail");
        assert!(error_text.to_string().contains("exit code 7"));
        assert!(error_text.to_string().contains("assist failed"));
    }
}