routa-core 0.15.1

Routa.js core domain — models, stores, protocols, and JSON-RPC (transport-agnostic)
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
//! RPC methods for Kanban board and card management.
//!
//! Methods:
//! - `kanban.listBoards`
//! - `kanban.createBoard`
//! - `kanban.getBoard`
//! - `kanban.updateBoard`
//! - `kanban.createCard`
//! - `kanban.moveCard`
//! - `kanban.updateCard`
//! - `kanban.deleteCard`
//! - `kanban.createColumn`
//! - `kanban.deleteColumn`
//! - `kanban.searchCards`
//! - `kanban.listCardsByColumn`
//! - `kanban.decomposeTasks`

mod automation;
mod boards;
mod cards;
mod handoffs;
mod queries;
mod shared;

pub use boards::{
    create_board, create_column, delete_column, get_board, list_boards, update_board,
    CreateBoardParams, CreateBoardResult, CreateColumnParams, CreateColumnResult,
    DeleteColumnParams, DeleteColumnResult, GetBoardParams, GetBoardResult, KanbanBoardSummary,
    KanbanColumnWithCards, ListBoardsParams, ListBoardsResult, UpdateBoardParams,
    UpdateBoardResult,
};
pub use cards::{
    create_card, decompose_tasks, delete_card, move_card, update_card, CreateCardParams,
    CreateCardResult, DecomposeTaskItem, DecomposeTasksParams, DecomposeTasksResult,
    DeleteCardParams, DeleteCardResult, MoveCardParams, MoveCardResult, UpdateCardParams,
    UpdateCardResult,
};
pub use handoffs::{
    request_previous_lane_handoff, submit_lane_handoff, RequestPreviousLaneHandoffParams,
    RequestPreviousLaneHandoffResult, SubmitLaneHandoffParams, SubmitLaneHandoffResult,
};
pub use queries::{
    list_cards_by_column, search_cards, ListCardsByColumnParams, ListCardsByColumnResult,
    SearchCardsParams, SearchCardsResult,
};

#[cfg(test)]
mod tests {
    use super::automation::{
        absolutize_url, apply_trigger_result, build_task_prompt, AgentTriggerResult,
    };
    use super::boards::build_board_result;
    use super::*;
    use chrono::Utc;

    use crate::db::Database;
    use crate::models::kanban::{
        KanbanAutomationStep, KanbanBoard, KanbanColumn, KanbanColumnAutomation, KanbanTransport,
    };
    use crate::models::task::{
        Task, TaskLaneHandoff, TaskLaneHandoffRequestType, TaskLaneHandoffStatus, TaskLaneSession,
        TaskLaneSessionStatus,
    };
    use crate::models::workspace::Workspace;
    use crate::rpc::error::RpcError;
    use crate::state::{AppState, AppStateInner};
    use std::sync::Arc;

    async fn setup_state() -> AppState {
        let db = Database::open_in_memory().expect("in-memory db should open");
        let state: AppState = Arc::new(AppStateInner::new(db));
        state
            .workspace_store
            .ensure_default()
            .await
            .expect("default workspace should exist");
        state
    }

    async fn populate_story_readiness_fields(state: &AppState, task_id: &str) {
        let mut task = state
            .task_store
            .get(task_id)
            .await
            .expect("task lookup should succeed")
            .expect("task should exist");
        task.scope = Some("Implement the requested change within the current lane.".to_string());
        task.acceptance_criteria = Some(vec![
            "The acceptance criteria are explicitly captured.".to_string()
        ]);
        task.verification_commands = Some(vec!["cargo test -p routa-core".to_string()]);
        state
            .task_store
            .save(&task)
            .await
            .expect("task should save");
    }

    #[tokio::test]
    async fn list_boards_ensures_default_board_exists() {
        let state = setup_state().await;

        let result = list_boards(
            &state,
            ListBoardsParams {
                workspace_id: "default".to_string(),
            },
        )
        .await
        .expect("list boards should succeed");

        assert_eq!(result.boards.len(), 1);
        assert!(result.boards[0].is_default);
        assert!(result.boards[0].column_count > 0);
    }

    #[tokio::test]
    async fn create_card_without_board_id_uses_default_board() {
        let state = setup_state().await;
        let boards = list_boards(
            &state,
            ListBoardsParams {
                workspace_id: "default".to_string(),
            },
        )
        .await
        .expect("list boards should succeed");
        let default_board_id = boards.boards[0].id.clone();

        let created = create_card(
            &state,
            CreateCardParams {
                workspace_id: "default".to_string(),
                board_id: None,
                column_id: Some("backlog".to_string()),
                title: "Implement RPC".to_string(),
                description: Some("wire core methods".to_string()),
                priority: Some("high".to_string()),
                labels: Some(vec!["rpc".to_string(), "kanban".to_string()]),
            },
        )
        .await
        .expect("create card should succeed");

        let board_view = get_board(
            &state,
            GetBoardParams {
                board_id: default_board_id,
            },
        )
        .await
        .expect("get board should succeed");

        let backlog = board_view
            .columns
            .iter()
            .find(|column| column.id == "backlog")
            .expect("backlog column should exist");
        assert_eq!(backlog.cards.len(), 1);
        assert_eq!(backlog.cards[0].id, created.card.id);
        assert_eq!(backlog.cards[0].priority.as_deref(), Some("high"));
    }

    #[tokio::test]
    async fn create_card_with_cross_workspace_board_id_falls_back_to_current_workspace_default() {
        let state = setup_state().await;
        state
            .workspace_store
            .save(&Workspace::new(
                "ws-other".to_string(),
                "Other Workspace".to_string(),
                None,
            ))
            .await
            .expect("other workspace should save");

        let foreign_board = create_board(
            &state,
            CreateBoardParams {
                workspace_id: "ws-other".to_string(),
                name: "Foreign Board".to_string(),
                columns: None,
                is_default: None,
                id: None,
            },
        )
        .await
        .expect("foreign board should create");

        let default_boards = list_boards(
            &state,
            ListBoardsParams {
                workspace_id: "default".to_string(),
            },
        )
        .await
        .expect("default boards should list");
        let default_board_id = default_boards.boards[0].id.clone();

        let created = create_card(
            &state,
            CreateCardParams {
                workspace_id: "default".to_string(),
                board_id: Some(foreign_board.board.id.clone()),
                column_id: Some("backlog".to_string()),
                title: "Stay in current workspace".to_string(),
                description: None,
                priority: None,
                labels: None,
            },
        )
        .await
        .expect("create card should fall back to current workspace default board");

        let task = state
            .task_store
            .get(&created.card.id)
            .await
            .expect("task lookup should succeed")
            .expect("task should exist");
        assert_eq!(task.workspace_id, "default");
        assert_eq!(task.board_id.as_deref(), Some(default_board_id.as_str()));
        assert_ne!(
            task.board_id.as_deref(),
            Some(foreign_board.board.id.as_str())
        );
    }

    #[test]
    fn build_task_prompt_includes_lane_specific_guidance() {
        let mut task = Task::new(
            "task-1".to_string(),
            "Implement Kanban RPC".to_string(),
            "Ship the kanban lane workflow".to_string(),
            "default".to_string(),
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        );
        task.column_id = Some("todo".to_string());
        task.labels = vec!["rpc".to_string(), "kanban".to_string()];

        let prompt = build_task_prompt(
            &task,
            Some("board-1"),
            Some("dev"),
            "- todo (Todo) stage=todo position=1\n- dev (Dev) stage=dev position=2",
            None,
            None,
            None,
        );

        assert!(prompt.contains("You are in the `todo` lane."));
        assert!(prompt.contains("Do not edit files"));
        assert!(prompt.contains("**Board ID:** board-1"));
        assert!(prompt.contains("targetColumnId `dev`"));
        assert!(prompt.contains("Labels: rpc, kanban"));
    }

    #[test]
    fn absolutize_url_resolves_relative_urls_against_agent_card() {
        let resolved = absolutize_url("https://example.com/.well-known/agent-card.json", "/rpc")
            .expect("relative URLs should resolve");

        assert_eq!(resolved, "https://example.com/rpc");
        assert_eq!(
            absolutize_url(
                "https://example.com/agent-card.json",
                "https://agent.example/rpc"
            )
            .expect("absolute URLs should pass through"),
            "https://agent.example/rpc"
        );
    }

    #[test]
    fn apply_trigger_result_tracks_session_history_for_current_lane() {
        let mut task = Task::new(
            "task-1".to_string(),
            "Implement lane automation".to_string(),
            "Move the task through the board".to_string(),
            "default".to_string(),
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        );
        task.column_id = Some("todo".to_string());
        task.assigned_provider = Some("opencode".to_string());
        task.assigned_role = Some("CRAFTER".to_string());
        task.assigned_specialist_id = Some("spec-1".to_string());
        task.assigned_specialist_name = Some("Todo Worker".to_string());

        let board = KanbanBoard {
            id: "board-1".to_string(),
            workspace_id: "default".to_string(),
            name: "Board".to_string(),
            is_default: true,
            columns: vec![KanbanColumn {
                id: "todo".to_string(),
                name: "Todo".to_string(),
                color: None,
                position: 1,
                stage: "todo".to_string(),
                automation: None,
                visible: Some(true),
                width: None,
            }],
            created_at: Utc::now(),
            updated_at: Utc::now(),
        };
        let step = KanbanAutomationStep {
            id: "step-1".to_string(),
            specialist_name: Some("Planner".to_string()),
            ..Default::default()
        };

        apply_trigger_result(
            &mut task,
            Some(&board),
            Some(&step),
            AgentTriggerResult {
                session_id: "session-1".to_string(),
                transport: "acp".to_string(),
                external_task_id: None,
                context_id: Some("ctx-1".to_string()),
            },
        );

        assert_eq!(task.trigger_session_id.as_deref(), Some("session-1"));
        assert_eq!(task.session_ids, vec!["session-1".to_string()]);
        assert_eq!(task.lane_sessions.len(), 1);

        let lane_session = &task.lane_sessions[0];
        assert_eq!(lane_session.session_id, "session-1");
        assert_eq!(lane_session.column_id.as_deref(), Some("todo"));
        assert_eq!(lane_session.column_name.as_deref(), Some("Todo"));
        assert_eq!(lane_session.step_id.as_deref(), Some("step-1"));
        assert_eq!(lane_session.step_name.as_deref(), Some("Planner"));
        assert_eq!(lane_session.provider.as_deref(), Some("opencode"));
        assert_eq!(lane_session.role.as_deref(), Some("CRAFTER"));
        assert_eq!(lane_session.transport.as_deref(), Some("acp"));
        assert_eq!(lane_session.context_id.as_deref(), Some("ctx-1"));
        assert_eq!(lane_session.status, TaskLaneSessionStatus::Running);
    }

    #[tokio::test]
    async fn build_board_result_sorts_cards_within_each_column_by_position() {
        let state = setup_state().await;
        let boards = list_boards(
            &state,
            ListBoardsParams {
                workspace_id: "default".to_string(),
            },
        )
        .await
        .expect("list boards should succeed");
        let board_id = boards.boards[0].id.clone();
        let board = state
            .kanban_store
            .get(&board_id)
            .await
            .expect("board load should succeed")
            .expect("default board should exist");

        let mut later = Task::new(
            "task-later".to_string(),
            "Later backlog task".to_string(),
            "Later".to_string(),
            "default".to_string(),
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        );
        later.board_id = Some(board.id.clone());
        later.column_id = Some("backlog".to_string());
        later.position = 2;

        let mut earlier = Task::new(
            "task-earlier".to_string(),
            "Earlier backlog task".to_string(),
            "Earlier".to_string(),
            "default".to_string(),
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        );
        earlier.board_id = Some(board.id.clone());
        earlier.column_id = Some("backlog".to_string());
        earlier.position = 1;

        state
            .task_store
            .save(&later)
            .await
            .expect("later task save should succeed");
        state
            .task_store
            .save(&earlier)
            .await
            .expect("earlier task save should succeed");

        let result = build_board_result(&state, board)
            .await
            .expect("board result should build");
        let backlog = result
            .columns
            .iter()
            .find(|column| column.id == "backlog")
            .expect("backlog column should exist");

        let backlog_ids: Vec<&str> = backlog.cards.iter().map(|card| card.id.as_str()).collect();
        assert_eq!(backlog_ids, vec!["task-earlier", "task-later"]);
    }

    #[tokio::test]
    async fn move_card_updates_status_and_rejects_negative_position() {
        let state = setup_state().await;
        let created = create_card(
            &state,
            CreateCardParams {
                workspace_id: "default".to_string(),
                board_id: None,
                column_id: Some("backlog".to_string()),
                title: "Move me".to_string(),
                description: None,
                priority: None,
                labels: None,
            },
        )
        .await
        .expect("create card should succeed");
        populate_story_readiness_fields(&state, &created.card.id).await;

        let moved = move_card(
            &state,
            MoveCardParams {
                card_id: created.card.id.clone(),
                target_column_id: "dev".to_string(),
                position: None,
            },
        )
        .await
        .expect("move card should succeed");
        assert_eq!(moved.card.column_id, "dev");
        assert_eq!(moved.card.status, "IN_PROGRESS");

        let err = move_card(
            &state,
            MoveCardParams {
                card_id: created.card.id,
                target_column_id: "review".to_string(),
                position: Some(-1),
            },
        )
        .await
        .expect_err("negative position should fail");
        assert!(matches!(err, RpcError::BadRequest(_)));
    }

    #[tokio::test]
    async fn update_card_rejects_description_changes_in_dev() {
        let state = setup_state().await;
        let created = create_card(
            &state,
            CreateCardParams {
                workspace_id: "default".to_string(),
                board_id: None,
                column_id: Some("backlog".to_string()),
                title: "Freeze description".to_string(),
                description: Some("Original story".to_string()),
                priority: None,
                labels: None,
            },
        )
        .await
        .expect("create card should succeed");
        populate_story_readiness_fields(&state, &created.card.id).await;
        move_card(
            &state,
            MoveCardParams {
                card_id: created.card.id.clone(),
                target_column_id: "dev".to_string(),
                position: None,
            },
        )
        .await
        .expect("move card should succeed");

        let err = update_card(
            &state,
            UpdateCardParams {
                card_id: created.card.id,
                title: None,
                description: Some("Rewrite in dev".to_string()),
                comment: None,
                priority: None,
                labels: None,
            },
        )
        .await
        .expect_err("description update in dev should fail");

        assert!(
            matches!(err, RpcError::BadRequest(message) if message.contains("comment field instead"))
        );
    }

    #[tokio::test]
    async fn update_card_appends_comment_without_rewriting_description() {
        let state = setup_state().await;
        let created = create_card(
            &state,
            CreateCardParams {
                workspace_id: "default".to_string(),
                board_id: None,
                column_id: Some("backlog".to_string()),
                title: "Append comment".to_string(),
                description: Some("Stable story".to_string()),
                priority: None,
                labels: None,
            },
        )
        .await
        .expect("create card should succeed");

        let first = update_card(
            &state,
            UpdateCardParams {
                card_id: created.card.id.clone(),
                title: None,
                description: None,
                comment: Some("First note".to_string()),
                priority: None,
                labels: None,
            },
        )
        .await
        .expect("first comment update should succeed");
        assert_eq!(first.card.comment.as_deref(), Some("First note"));

        let second = update_card(
            &state,
            UpdateCardParams {
                card_id: created.card.id.clone(),
                title: None,
                description: None,
                comment: Some("Second note".to_string()),
                priority: None,
                labels: None,
            },
        )
        .await
        .expect("second comment update should succeed");
        assert_eq!(
            second.card.comment.as_deref(),
            Some("First note\n\nSecond note")
        );

        let saved = state
            .task_store
            .get(&created.card.id)
            .await
            .expect("task lookup should succeed")
            .expect("task should exist");
        assert_eq!(saved.objective, "Stable story");
        assert_eq!(saved.comment.as_deref(), Some("First note\n\nSecond note"));
    }

    #[tokio::test]
    async fn move_card_applies_lane_automation_defaults_to_task() {
        let state = setup_state().await;
        let boards = list_boards(
            &state,
            ListBoardsParams {
                workspace_id: "default".to_string(),
            },
        )
        .await
        .expect("list boards should succeed");
        let board_id = boards.boards[0].id.clone();

        let mut board = state
            .kanban_store
            .get(&board_id)
            .await
            .expect("board load should succeed")
            .expect("default board should exist");
        let todo = board
            .columns
            .iter_mut()
            .find(|column| column.id == "todo")
            .expect("todo column should exist");
        todo.automation = Some(KanbanColumnAutomation {
            enabled: true,
            provider_id: Some("opencode".to_string()),
            role: Some("CRAFTER".to_string()),
            specialist_id: Some("kanban-todo-worker".to_string()),
            specialist_name: Some("Todo Worker".to_string()),
            transition_type: Some("entry".to_string()),
            ..Default::default()
        });
        state
            .kanban_store
            .update(&board)
            .await
            .expect("board update should succeed");

        let created = create_card(
            &state,
            CreateCardParams {
                workspace_id: "default".to_string(),
                board_id: Some(board_id.clone()),
                column_id: Some("backlog".to_string()),
                title: "Automate me".to_string(),
                description: None,
                priority: None,
                labels: None,
            },
        )
        .await
        .expect("create card should succeed");
        move_card(
            &state,
            MoveCardParams {
                card_id: created.card.id.clone(),
                target_column_id: "todo".to_string(),
                position: None,
            },
        )
        .await
        .expect("move card should succeed");

        let task = state
            .task_store
            .get(&created.card.id)
            .await
            .expect("task lookup should succeed")
            .expect("task should exist");
        assert_eq!(task.assigned_provider.as_deref(), Some("opencode"));
        assert_eq!(task.assigned_role.as_deref(), Some("CRAFTER"));
        assert_eq!(
            task.assigned_specialist_id.as_deref(),
            Some("kanban-backlog-refiner")
        );
        assert_eq!(
            task.assigned_specialist_name.as_deref(),
            Some("Backlog Refiner")
        );
        assert!(
            task.trigger_session_id.is_some() || task.last_sync_error.is_some(),
            "lane automation should either start a session or record why it could not"
        );
    }

    #[tokio::test]
    async fn move_card_routes_a2a_lane_automation_without_falling_back_to_acp() {
        let state = setup_state().await;
        let boards = list_boards(
            &state,
            ListBoardsParams {
                workspace_id: "default".to_string(),
            },
        )
        .await
        .expect("list boards should succeed");
        let board_id = boards.boards[0].id.clone();

        let mut board = state
            .kanban_store
            .get(&board_id)
            .await
            .expect("board load should succeed")
            .expect("default board should exist");
        let todo = board
            .columns
            .iter_mut()
            .find(|column| column.id == "todo")
            .expect("todo column should exist");
        todo.automation = Some(KanbanColumnAutomation {
            enabled: true,
            steps: Some(vec![KanbanAutomationStep {
                id: "todo-a2a".to_string(),
                transport: Some(KanbanTransport::A2a),
                provider_id: None,
                role: Some("CRAFTER".to_string()),
                specialist_id: None,
                specialist_name: Some("Todo Remote Worker".to_string()),
                agent_card_url: Some("http://127.0.0.1:9/card".to_string()),
                skill_id: Some("remote-skill".to_string()),
                auth_config_id: None,
            }]),
            transition_type: Some("entry".to_string()),
            ..Default::default()
        });
        state
            .kanban_store
            .update(&board)
            .await
            .expect("board update should succeed");

        let created = create_card(
            &state,
            CreateCardParams {
                workspace_id: "default".to_string(),
                board_id: Some(board_id.clone()),
                column_id: Some("backlog".to_string()),
                title: "Automate remotely".to_string(),
                description: None,
                priority: None,
                labels: None,
            },
        )
        .await
        .expect("create card should succeed");
        let created_task = state
            .task_store
            .get(&created.card.id)
            .await
            .expect("task lookup should succeed")
            .expect("task should exist after create");
        let existing_session_ids = created_task.session_ids.clone();
        let existing_lane_sessions = created_task.lane_sessions.clone();

        move_card(
            &state,
            MoveCardParams {
                card_id: created.card.id.clone(),
                target_column_id: "todo".to_string(),
                position: None,
            },
        )
        .await
        .expect("move card should succeed");

        let task = state
            .task_store
            .get(&created.card.id)
            .await
            .expect("task lookup should succeed")
            .expect("task should exist");
        assert!(
            task.trigger_session_id.is_none(),
            "failed A2A triggers must not silently create ACP sessions"
        );
        assert!(
            task.last_sync_error
                .as_deref()
                .is_some_and(|message| message.contains("A2A") || message.contains("a2a")),
            "expected a2a-specific error, got {:?}",
            task.last_sync_error
        );
        assert_eq!(task.session_ids, existing_session_ids);
        assert_eq!(task.lane_sessions, existing_lane_sessions);
        assert!(
            task.lane_sessions
                .iter()
                .all(|session| session.transport.as_deref() != Some("a2a")),
            "failed A2A transitions must not append A2A lane sessions"
        );
    }

    #[tokio::test]
    async fn move_card_blocks_transition_when_required_artifacts_are_missing() {
        let state = setup_state().await;
        let boards = list_boards(
            &state,
            ListBoardsParams {
                workspace_id: "default".to_string(),
            },
        )
        .await
        .expect("list boards should succeed");
        let board_id = boards.boards[0].id.clone();

        let mut board = state
            .kanban_store
            .get(&board_id)
            .await
            .expect("board load should succeed")
            .expect("default board should exist");
        let review = board
            .columns
            .iter_mut()
            .find(|column| column.id == "review")
            .expect("review column should exist");
        review.automation = Some(KanbanColumnAutomation {
            enabled: true,
            required_artifacts: Some(vec!["screenshot".to_string()]),
            ..Default::default()
        });
        state
            .kanban_store
            .update(&board)
            .await
            .expect("board update should succeed");

        let created = create_card(
            &state,
            CreateCardParams {
                workspace_id: "default".to_string(),
                board_id: Some(board_id),
                column_id: Some("todo".to_string()),
                title: "Need screenshot".to_string(),
                description: None,
                priority: None,
                labels: None,
            },
        )
        .await
        .expect("create card should succeed");

        let err = move_card(
            &state,
            MoveCardParams {
                card_id: created.card.id,
                target_column_id: "review".to_string(),
                position: None,
            },
        )
        .await
        .expect_err("transition should be blocked");

        assert!(
            matches!(err, RpcError::BadRequest(message) if message.contains("missing required artifacts: screenshot"))
        );
    }

    #[tokio::test]
    async fn move_card_blocks_transition_when_required_task_fields_are_missing() {
        let state = setup_state().await;
        let boards = list_boards(
            &state,
            ListBoardsParams {
                workspace_id: "default".to_string(),
            },
        )
        .await
        .expect("list boards should succeed");
        let board_id = boards.boards[0].id.clone();

        let mut board = state
            .kanban_store
            .get(&board_id)
            .await
            .expect("board load should succeed")
            .expect("default board should exist");
        let dev = board
            .columns
            .iter_mut()
            .find(|column| column.id == "dev")
            .expect("dev column should exist");
        dev.automation = Some(KanbanColumnAutomation {
            enabled: true,
            required_task_fields: Some(vec![
                "scope".to_string(),
                "acceptance_criteria".to_string(),
                "verification_plan".to_string(),
            ]),
            ..Default::default()
        });
        state
            .kanban_store
            .update(&board)
            .await
            .expect("board update should succeed");

        let created = create_card(
            &state,
            CreateCardParams {
                workspace_id: "default".to_string(),
                board_id: Some(board_id),
                column_id: Some("todo".to_string()),
                title: "Need scope".to_string(),
                description: Some("Missing scope and verification plan".to_string()),
                priority: None,
                labels: None,
            },
        )
        .await
        .expect("create card should succeed");

        let err = move_card(
            &state,
            MoveCardParams {
                card_id: created.card.id,
                target_column_id: "dev".to_string(),
                position: None,
            },
        )
        .await
        .expect_err("transition should be blocked");

        assert!(
            matches!(err, RpcError::BadRequest(message) if message.contains("missing required task fields"))
        );
    }

    #[tokio::test]
    async fn delete_column_moves_cards_to_backlog_when_not_deleting_cards() {
        let state = setup_state().await;
        let created = create_card(
            &state,
            CreateCardParams {
                workspace_id: "default".to_string(),
                board_id: None,
                column_id: Some("todo".to_string()),
                title: "Todo card".to_string(),
                description: None,
                priority: None,
                labels: None,
            },
        )
        .await
        .expect("create card should succeed");

        let board_before = list_boards(
            &state,
            ListBoardsParams {
                workspace_id: "default".to_string(),
            },
        )
        .await
        .expect("list boards should succeed");
        let board_id = board_before.boards[0].id.clone();

        let result = delete_column(
            &state,
            DeleteColumnParams {
                board_id: board_id.clone(),
                column_id: "todo".to_string(),
                delete_cards: Some(false),
            },
        )
        .await
        .expect("delete column should succeed");

        assert!(result.deleted);
        assert_eq!(result.cards_moved, 1);
        assert_eq!(result.cards_deleted, 0);
        assert!(!result
            .board
            .columns
            .iter()
            .any(|column| column.id == "todo"));

        let task = state
            .task_store
            .get(&created.card.id)
            .await
            .expect("task get should succeed")
            .expect("task should still exist");
        assert_eq!(task.column_id.as_deref(), Some("backlog"));
    }

    #[tokio::test]
    async fn search_list_by_column_and_decompose_tasks_work() {
        let state = setup_state().await;
        let first = create_card(
            &state,
            CreateCardParams {
                workspace_id: "default".to_string(),
                board_id: None,
                column_id: Some("backlog".to_string()),
                title: "Searchable API card".to_string(),
                description: None,
                priority: None,
                labels: Some(vec!["api".to_string()]),
            },
        )
        .await
        .expect("create card should succeed");
        let second = create_card(
            &state,
            CreateCardParams {
                workspace_id: "default".to_string(),
                board_id: None,
                column_id: Some("backlog".to_string()),
                title: "Another card".to_string(),
                description: None,
                priority: None,
                labels: None,
            },
        )
        .await
        .expect("create card should succeed");
        populate_story_readiness_fields(&state, &second.card.id).await;
        move_card(
            &state,
            MoveCardParams {
                card_id: second.card.id.clone(),
                target_column_id: "dev".to_string(),
                position: Some(0),
            },
        )
        .await
        .expect("move should succeed");

        let boards = list_boards(
            &state,
            ListBoardsParams {
                workspace_id: "default".to_string(),
            },
        )
        .await
        .expect("list boards should succeed");
        let board_id = boards.boards[0].id.clone();

        let searched = search_cards(
            &state,
            SearchCardsParams {
                workspace_id: "default".to_string(),
                query: "api".to_string(),
                board_id: Some(board_id.clone()),
            },
        )
        .await
        .expect("search should succeed");
        assert_eq!(searched.cards.len(), 1);
        assert_eq!(searched.cards[0].id, first.card.id);

        let dev_cards = list_cards_by_column(
            &state,
            ListCardsByColumnParams {
                workspace_id: "default".to_string(),
                board_id: Some(board_id.clone()),
                column_id: "dev".to_string(),
            },
        )
        .await
        .expect("list cards by column should succeed");
        assert_eq!(dev_cards.cards.len(), 1);
        assert_eq!(dev_cards.cards[0].id, second.card.id);

        let decomposed = decompose_tasks(
            &state,
            DecomposeTasksParams {
                workspace_id: "default".to_string(),
                board_id: Some(board_id),
                column_id: Some("backlog".to_string()),
                tasks: vec![
                    DecomposeTaskItem {
                        title: "Split 1".to_string(),
                        description: Some("a".to_string()),
                        priority: Some("low".to_string()),
                        labels: None,
                    },
                    DecomposeTaskItem {
                        title: "Split 2".to_string(),
                        description: None,
                        priority: Some("urgent".to_string()),
                        labels: Some(vec!["bulk".to_string()]),
                    },
                ],
            },
        )
        .await
        .expect("decompose should succeed");
        assert_eq!(decomposed.count, 2);
        assert_eq!(decomposed.cards.len(), 2);
    }

    #[tokio::test]
    async fn request_previous_lane_handoff_persists_failed_delivery() {
        let state = setup_state().await;
        let boards = list_boards(
            &state,
            ListBoardsParams {
                workspace_id: "default".to_string(),
            },
        )
        .await
        .expect("list boards should succeed");
        let board_id = boards.boards[0].id.clone();

        let mut task = Task::new(
            "task-handoff".to_string(),
            "Review failing runtime".to_string(),
            "Need help from the previous lane".to_string(),
            "default".to_string(),
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        );
        task.board_id = Some(board_id);
        task.column_id = Some("review".to_string());
        task.lane_sessions = vec![
            TaskLaneSession {
                session_id: "session-dev".to_string(),
                routa_agent_id: None,
                column_id: Some("dev".to_string()),
                column_name: Some("Dev".to_string()),
                step_id: None,
                step_index: None,
                step_name: None,
                provider: None,
                role: None,
                specialist_id: None,
                specialist_name: None,
                transport: None,
                external_task_id: None,
                context_id: None,
                attempt: None,
                loop_mode: None,
                completion_requirement: None,
                objective: None,
                last_activity_at: None,
                recovered_from_session_id: None,
                recovery_reason: None,
                status: TaskLaneSessionStatus::Completed,
                started_at: Utc::now().to_rfc3339(),
                completed_at: None,
            },
            TaskLaneSession {
                session_id: "session-review".to_string(),
                routa_agent_id: None,
                column_id: Some("review".to_string()),
                column_name: Some("Review".to_string()),
                step_id: None,
                step_index: None,
                step_name: None,
                provider: None,
                role: None,
                specialist_id: None,
                specialist_name: None,
                transport: None,
                external_task_id: None,
                context_id: None,
                attempt: None,
                loop_mode: None,
                completion_requirement: None,
                objective: None,
                last_activity_at: None,
                recovered_from_session_id: None,
                recovery_reason: None,
                status: TaskLaneSessionStatus::Running,
                started_at: Utc::now().to_rfc3339(),
                completed_at: None,
            },
        ];
        state
            .task_store
            .save(&task)
            .await
            .expect("task save should succeed");

        let result = request_previous_lane_handoff(
            &state,
            RequestPreviousLaneHandoffParams {
                task_id: task.id.clone(),
                request_type: "runtime_context".to_string(),
                request: "Please share the startup steps".to_string(),
                session_id: "session-review".to_string(),
            },
        )
        .await
        .expect("handoff request should succeed");

        assert_eq!(result.status, TaskLaneHandoffStatus::Failed);
        assert_eq!(result.target_session_id, "session-dev");

        let saved = state
            .task_store
            .get(&task.id)
            .await
            .expect("task get should succeed")
            .expect("task should exist");
        assert_eq!(saved.lane_handoffs.len(), 1);
        assert_eq!(
            saved.lane_handoffs[0].request_type,
            TaskLaneHandoffRequestType::RuntimeContext
        );
        assert_eq!(saved.lane_handoffs[0].status, TaskLaneHandoffStatus::Failed);
        assert!(saved.lane_handoffs[0].response_summary.is_some());
    }

    #[tokio::test]
    async fn submit_lane_handoff_updates_existing_record() {
        let state = setup_state().await;

        let mut task = Task::new(
            "task-handoff-submit".to_string(),
            "Respond to lane request".to_string(),
            "Return environment details".to_string(),
            "default".to_string(),
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        );
        task.lane_handoffs = vec![TaskLaneHandoff {
            id: "handoff-1".to_string(),
            from_session_id: "session-review".to_string(),
            to_session_id: "session-dev".to_string(),
            from_column_id: Some("review".to_string()),
            to_column_id: Some("dev".to_string()),
            request_type: TaskLaneHandoffRequestType::RuntimeContext,
            request: "Please share the command".to_string(),
            status: TaskLaneHandoffStatus::Delivered,
            requested_at: Utc::now().to_rfc3339(),
            responded_at: None,
            response_summary: None,
        }];
        state
            .task_store
            .save(&task)
            .await
            .expect("task save should succeed");

        let result = submit_lane_handoff(
            &state,
            SubmitLaneHandoffParams {
                task_id: task.id.clone(),
                handoff_id: "handoff-1".to_string(),
                status: "completed".to_string(),
                summary: "Environment prepared and command rerun".to_string(),
                session_id: "session-dev".to_string(),
            },
        )
        .await
        .expect("handoff submit should succeed");

        assert_eq!(result.status, TaskLaneHandoffStatus::Completed);

        let saved = state
            .task_store
            .get(&task.id)
            .await
            .expect("task get should succeed")
            .expect("task should exist");
        assert_eq!(
            saved.lane_handoffs[0].status,
            TaskLaneHandoffStatus::Completed
        );
        assert_eq!(
            saved.lane_handoffs[0].response_summary.as_deref(),
            Some("Environment prepared and command rerun")
        );
        assert!(saved.lane_handoffs[0].responded_at.is_some());
    }
}