onetaskgraph 0.3.1

One interface over the ticketing systems your work lives in.
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
//! What a plan and a follow-up flow write to a Linear source, driven the way a user drives it.
//!
//! Every journey spawns the compiled binary against the shared stateful fake Linear — a real
//! HTTP server whose one team carries the Hello Patient team's workflow state names and types,
//! two of type `backlog` and two of type `unstarted` among them, so a state written by name and
//! one written as the first of its type land in different places. Each asserts on the exit
//! code, stdout and stderr, and on what the workspace holds afterwards — its raw descriptions
//! byte for byte, and every request it was sent.

use std::path::{Path, PathBuf};
use std::process::Output;

use serde_json::{Value, json};

use crate::common::{Sandbox, stderr, stdout};
use crate::fixtures::{LINEAR_TEAM_STATES, LinearWorkspace, document, linear_workspace};

/// The eight-entry mapping the Hello Patient team is configured with.
fn eng_mapping() -> Value {
    json!({
        "backlog": "Proposed",
        "draft": "Backlog",
        "todo": "Todo",
        "queued": "Queued",
        "in-progress": "In Progress",
        "unknown": "Needs Attention",
        "done": "Done",
        "cancelled": "Canceled",
    })
}

/// Every category, in the order a cycle through them never repeats one.
const CATEGORIES: [&str; 8] = [
    "draft",
    "backlog",
    "todo",
    "queued",
    "in-progress",
    "unknown",
    "done",
    "cancelled",
];

fn run(sandbox: &Sandbox, arguments: &[&str]) -> Output {
    sandbox
        .command()
        .args(arguments)
        .assert()
        .get_output()
        .clone()
}

/// A run that had to exit `code`, quoting what it said when it did not.
fn exits(sandbox: &Sandbox, arguments: &[&str], code: i32) -> Output {
    let output = run(sandbox, arguments);
    assert_eq!(
        output.status.code(),
        Some(code),
        "`onetaskgraph {}` exited {:?}\nstdout:\n{}\nstderr:\n{}",
        arguments.join(" "),
        output.status.code(),
        stdout(&output),
        stderr(&output)
    );
    output
}

/// A run that had to succeed with one JSON document on stdout.
fn answered(sandbox: &Sandbox, arguments: &[&str]) -> Value {
    let output = exits(sandbox, arguments, 0);
    serde_json::from_str(&stdout(&output)).unwrap_or_else(|error| {
        panic!(
            "`onetaskgraph {}` wrote no JSON ({error}):\n{}",
            arguments.join(" "),
            stdout(&output)
        )
    })
}

/// One task as `task show --json` reads it back.
fn shown(sandbox: &Sandbox, id: &str) -> Value {
    answered(sandbox, &["--json", "task", "show", id])["items"][0]["item"].clone()
}

/// The status a task reads back as, as `[category, name]`.
fn status(sandbox: &Sandbox, id: &str) -> Value {
    let item = shown(sandbox, id);
    json!([item["status"]["category"], item["status"]["name"]])
}

/// The type the team gives the workflow state `name`.
fn type_of(name: &str) -> &'static str {
    LINEAR_TEAM_STATES
        .iter()
        .find(|state| state.1 == name)
        .unwrap_or_else(|| panic!("the team has no state {name}"))
        .2
}

/// One issue held at the team's workflow state `state`.
fn issue(id: &str, state: &str, extra: Value) -> Value {
    let kind = type_of(state);
    let category = match kind {
        "unstarted" => "todo",
        "started" => "in-progress",
        "completed" => "done",
        "canceled" => "cancelled",
        "backlog" => "backlog",
        _ => "unknown",
    };
    let mut row = json!({
        "id": id, "title": format!("Issue {id}"), "content": format!("The body of {id}."),
        "status": {"name": state, "category": category},
        "_linear_state": {"name": state, "type": kind},
        "labels": [], "priority": "none",
    });
    for (key, value) in extra.as_object().expect("an object") {
        row[key] = value.clone();
    }
    row
}

/// A workspace holding exactly `tasks`, `projects` and `documents`.
fn held(tasks: Vec<Value>, projects: Vec<Value>, documents: Vec<Value>) -> Value {
    json!({
        "tasks": tasks, "projects": projects, "documents": documents, "labels": [],
        "task_dependencies": [], "project_dependencies": [],
    })
}

fn project(id: &str) -> Value {
    json!({"id": id, "title": format!("Project {id}"), "content": format!("About {id}."),
           "status": {"category": "in-progress", "name": "Doing"}, "labels": []})
}

/// A folder of Markdown holding `files`, whose status words are the category words.
fn folder(sandbox: &Sandbox, name: &str, files: &[(&str, &str)]) -> PathBuf {
    let root = sandbox.subdirectory(name);
    for kind in ["tasks", "projects", "documents"] {
        std::fs::create_dir_all(root.join(kind)).expect("a folder");
    }
    for (relative, text) in files {
        std::fs::write(root.join(relative), text).expect("a file");
    }
    root
}

fn markdown(root: &Path) -> Value {
    let words = CATEGORIES
        .iter()
        .map(|category| ((*category).to_owned(), json!(category)))
        .collect::<serde_json::Map<_, _>>();
    json!({"plugin": "local-md", "config": {"root": root, "status_mapping": words}})
}

/// The Linear source configured over `config`, with `extra` beside the fake's own keys.
fn linear(config: &Value, extra: Value) -> Value {
    let mut config = config.clone();
    for (key, value) in extra.as_object().expect("an object") {
        config[key] = value.clone();
    }
    json!({"plugin": "linear", "config": config})
}

/// Every mutation the workspace answered after the `from`th request, by its root field.
fn mutations_since(workspace: &LinearWorkspace, from: usize) -> Vec<String> {
    workspace
        .served()
        .into_iter()
        .skip(from)
        .filter(|(query, _)| query.trim_start().starts_with("mutation"))
        .map(|(query, _)| {
            query
                .split_once('{')
                .and_then(|(_, rest)| rest.trim_start().split('(').next())
                .unwrap_or_default()
                .to_owned()
        })
        .collect()
}

/// A body file under the sandbox.
fn body(sandbox: &Sandbox, text: &str) -> String {
    let path = sandbox.subdirectory("bodies").join("body.md");
    std::fs::write(&path, text).expect("a body file");
    path.to_string_lossy().into_owned()
}

/// The workspace a scoped source reads: two projects of the team, an issue and a document in
/// each, and one issue in none.
fn scoped_workspace(sandbox: &Sandbox) -> (Value, LinearWorkspace) {
    // LP-1 is the counterpart of the plan's project PX, so a copy of PX updates the one
    // project a scoped source holds.
    let mut scope = project("LP-1");
    scope["metadata"] = json!({"onetaskgraph.origin": "plan:PX"});
    linear_workspace(
        sandbox,
        held(
            vec![
                issue("I-IN", "Todo", json!({"project": "LP-1"})),
                issue("I-OUT", "Todo", json!({"project": "LP-2"})),
                issue("I-NONE", "Todo", json!({})),
            ],
            vec![scope, project("LP-2")],
            vec![
                json!({"id": "D-IN", "title": "In", "content": "in", "project": "LP-1", "labels": []}),
                json!({"id": "D-OUT", "title": "Out", "content": "out", "project": "LP-2", "labels": []}),
            ],
        ),
    )
}

fn ids(answer: &Value) -> Vec<String> {
    answer["items"]
        .as_array()
        .expect("a page")
        .iter()
        .map(|item| item["id"].as_str().expect("an id").to_owned())
        .collect()
}

#[test]
fn a_project_scoped_linear_source_reads_and_writes_that_project_alone() {
    let sandbox = Sandbox::new();
    let (config, workspace) = scoped_workspace(&sandbox);
    let plan = folder(
        &sandbox,
        "plan",
        &[
            (
                "tasks/F-1.md",
                "---\ntitle: From the plan\nstatus: todo\n---\nbody\n",
            ),
            (
                "projects/PX.md",
                "---\ntitle: The scope's own\nstatus: todo\n---\nbody\n",
            ),
            (
                "projects/PY.md",
                "---\ntitle: Another project\nstatus: todo\n---\nbody\n",
            ),
            ("documents/D-1.md", "---\ntitle: A plan note\n---\nnote\n"),
        ],
    );
    sandbox.project_document(&document(&json!({
        "scoped": linear(&config, json!({"project": "LP-1"})),
        "wide": linear(&config, json!({})),
        "plan": markdown(&plan),
    })));

    assert_eq!(
        ids(&answered(
            &sandbox,
            &["--json", "task", "list", "--source", "scoped"]
        )),
        ["scoped:I-IN"]
    );
    assert_eq!(
        ids(&answered(
            &sandbox,
            &["--json", "project", "list", "--source", "scoped"]
        )),
        ["scoped:LP-1"]
    );
    assert_eq!(
        ids(&answered(
            &sandbox,
            &["--json", "document", "list", "--source", "scoped"]
        )),
        ["scoped:D-IN"]
    );
    // A read by id of anything filed elsewhere is no item of this source, and a document
    // query naming another project holds nothing.
    for (verb, id) in [
        ("task", "scoped:I-OUT"),
        ("project", "scoped:LP-2"),
        ("document", "scoped:D-OUT"),
    ] {
        exits(&sandbox, &[verb, "show", id], 1);
    }
    assert_eq!(
        ids(&answered(
            &sandbox,
            &[
                "--json",
                "document",
                "list",
                "--source",
                "scoped",
                "--project",
                "LP-2"
            ]
        )),
        Vec::<String>::new()
    );

    // Without the key, the same workspace reads team-wide.
    assert_eq!(
        ids(&answered(
            &sandbox,
            &["--json", "task", "list", "--source", "wide"]
        )),
        ["wide:I-IN", "wide:I-OUT", "wide:I-NONE"]
    );
    assert_eq!(
        ids(&answered(
            &sandbox,
            &["--json", "project", "list", "--source", "wide"]
        )),
        ["wide:LP-1", "wide:LP-2"]
    );

    // A task copied in with no project is placed in the scope.
    let copied = answered(
        &sandbox,
        &["--json", "task", "copy", "plan:F-1", "--to", "scoped"],
    );
    let destination = copied["items"][0]["destination"]
        .as_str()
        .expect("a destination")
        .split_once(':')
        .expect("source:native")
        .1
        .to_owned();
    assert_eq!(workspace.project_of(&destination).as_deref(), Some("LP-1"));
    assert!(
        ids(&answered(
            &sandbox,
            &["--json", "task", "list", "--source", "scoped"]
        ))
        .contains(&format!("scoped:{destination}")),
        "the copy reads back through the scoped source"
    );

    // One created in the scope lands there; one naming another project is refused naming both.
    let file = body(&sandbox, "A created body.");
    answered(
        &sandbox,
        &[
            "--json",
            "task",
            "create",
            "scoped",
            "--project",
            "LP-1",
            "--title",
            "Scoped",
            "--body-file",
            &file,
        ],
    );
    let created = workspace.issue_titled("Scoped").expect("created");
    assert_eq!(workspace.project_of(&created).as_deref(), Some("LP-1"));
    let from = workspace.served().len();
    let refused = exits(
        &sandbox,
        &[
            "task",
            "create",
            "scoped",
            "--project",
            "LP-2",
            "--title",
            "Elsewhere",
            "--body-file",
            &file,
        ],
        1,
    );
    let said = stderr(&refused);
    assert!(said.contains("LP-1") && said.contains("LP-2"), "{said}");
    assert_eq!(mutations_since(&workspace, from), Vec::<String>::new());

    // A document copied in with no project is filed under the scope; one created naming
    // another project is refused naming both.
    let copied = answered(
        &sandbox,
        &["--json", "document", "copy", "plan:D-1", "--to", "scoped"],
    );
    let destination = copied["items"][0]["destination"]
        .as_str()
        .expect("a destination")
        .split_once(':')
        .expect("source:native")
        .1
        .to_owned();
    assert_eq!(
        workspace.document_project(&destination).as_deref(),
        Some("LP-1")
    );
    let from = workspace.served().len();
    let refused = exits(
        &sandbox,
        &[
            "document",
            "create",
            "scoped",
            "--project",
            "LP-2",
            "--title",
            "Elsewhere",
            "--body-file",
            &file,
        ],
        1,
    );
    let said = stderr(&refused);
    assert!(said.contains("LP-1") && said.contains("LP-2"), "{said}");
    assert_eq!(mutations_since(&workspace, from), Vec::<String>::new());
    answered(
        &sandbox,
        &[
            "--json",
            "document",
            "create",
            "scoped",
            "--project",
            "LP-1",
            "--title",
            "Scoped note",
            "--body-file",
            &file,
        ],
    );
    let created = workspace.document_titled("Scoped note").expect("created");
    assert_eq!(
        workspace.document_project(&created).as_deref(),
        Some("LP-1")
    );

    // The one project it holds is updated by a copy of its counterpart; any other project is
    // refused naming the scope, writing nothing.
    let updated = answered(
        &sandbox,
        &["--json", "project", "copy", "plan:PX", "--to", "scoped"],
    );
    assert_eq!(
        updated["items"][0]["destination"], "scoped:LP-1",
        "{updated:#}"
    );
    let from = workspace.served().len();
    let refused = exits(
        &sandbox,
        &["project", "copy", "plan:PY", "--to", "scoped"],
        1,
    );
    let said = stderr(&refused);
    assert!(said.contains("scoped to the Linear project LP-1"), "{said}");
    assert_eq!(mutations_since(&workspace, from), Vec::<String>::new());
}

/// The GraphQL documents of every request the workspace answered after the `from`th.
fn documents_since(workspace: &LinearWorkspace, from: usize) -> Vec<String> {
    workspace
        .served()
        .into_iter()
        .skip(from)
        .map(|(query, _)| query)
        .collect()
}

#[test]
fn a_project_scoped_linear_source_writes_a_status_to_the_issue_it_names_wherever_it_is_filed() {
    let sandbox = Sandbox::new();
    let (config, workspace) = scoped_workspace(&sandbox);
    let plan = folder(
        &sandbox,
        "plan",
        &[(
            "projects/PY.md",
            "---\ntitle: Another project\nstatus: done\n---\nbody\n",
        )],
    );
    sandbox.project_document(&document(&json!({
        "scoped": linear(&config, json!({"project": "LP-1"})),
        "plan": markdown(&plan),
    })));
    let resolution = onetaskgraph_linear::graphql::RESOLUTION.to_owned();
    let mutation = onetaskgraph_linear::graphql::ISSUE_UPDATE_READ.to_owned();

    // An issue of the team filed in another project, named outright: the resolution and the
    // one mutation, no read before it, and the issue answered as it now reads.
    let from = workspace.served().len();
    let answer = answered(
        &sandbox,
        &["--json", "task", "status", "set", "scoped:I-OUT", "done"],
    );
    assert_eq!(answer["id"], "scoped:I-OUT", "{answer:#}");
    assert_eq!(
        answer["status"],
        json!({"category": "done", "name": "Shipped"}),
        "{answer:#}"
    );
    assert_eq!(
        documents_since(&workspace, from),
        [resolution.clone(), mutation.clone()]
    );
    assert_eq!(workspace.state_of("I-OUT").as_deref(), Some("Shipped"));
    // And a targeted update naming the status alone, the same.
    let from = workspace.served().len();
    answered(
        &sandbox,
        &[
            "--json",
            "task",
            "update",
            "scoped:I-OUT",
            "--status",
            "in-progress",
        ],
    );
    assert_eq!(
        documents_since(&workspace, from),
        [resolution.clone(), mutation.clone()]
    );
    assert_eq!(workspace.state_of("I-OUT").as_deref(), Some("Doing"));
    // Its own project's issue, at the same cost.
    let from = workspace.served().len();
    answered(
        &sandbox,
        &["--json", "task", "status", "set", "scoped:I-IN", "done"],
    );
    assert_eq!(documents_since(&workspace, from), [resolution, mutation]);
    assert_eq!(workspace.state_of("I-IN").as_deref(), Some("Shipped"));

    // Everything else is still scoped: the issue written is no item of this source to read or
    // list, and a write to another project is refused naming the scope before any request
    // `write_project` sends — the copy's own discovery is all that reaches the workspace.
    exits(&sandbox, &["task", "show", "scoped:I-OUT"], 1);
    assert_eq!(
        ids(&answered(
            &sandbox,
            &["--json", "task", "list", "--source", "scoped"]
        )),
        ["scoped:I-IN"]
    );
    let from = workspace.served().len();
    let refused = exits(
        &sandbox,
        &["project", "copy", "plan:PY", "--to", "scoped", "--no-tasks"],
        1,
    );
    let said = stderr(&refused);
    assert!(said.contains("scoped to the Linear project LP-1"), "{said}");
    assert_eq!(mutations_since(&workspace, from), Vec::<String>::new());
    let written = [
        onetaskgraph_linear::graphql::RESOLUTION,
        onetaskgraph_linear::graphql::PROJECT_LABEL,
        onetaskgraph_linear::graphql::PROJECT_CREATE,
        onetaskgraph_linear::graphql::PROJECT_REWRITE,
    ];
    assert!(
        documents_since(&workspace, from)
            .iter()
            .all(|query| !written.contains(&query.as_str())),
        "write_project sent a request before refusing"
    );
}

/// An issue, a project and a document each carrying prose with its own spacing and a slot
/// closed the way Linear hands one back.
fn slotted_workspace(sandbox: &Sandbox) -> (Value, LinearWorkspace) {
    let held_slot = "Prose a person wrote,\n\n   spaced their own way.  \n\n<!-- onetaskgraph.metadata\n{\"caller.kept\":[1,{\"deep\":true}]}\n\\-->";
    let mut task = issue("I-M", "Todo", json!({"project": "LP-1"}));
    task["_linear_description"] = json!(held_slot);
    let mut item = project("LP-1");
    item["_linear_description"] = json!(held_slot);
    linear_workspace(
        sandbox,
        held(
            vec![task],
            vec![item],
            vec![
                json!({"id": "D-M", "title": "A document", "content": "", "project": "LP-1",
                        "labels": [], "_linear_description": held_slot}),
            ],
        ),
    )
}

/// `field` split at its trailing slot: the bytes above it, and the slot's parsed JSON.
///
/// Either spelling: the one-line code span a source writes, and the multi-line one a
/// workspace seeded before it holds.
fn split_slot(field: &str) -> (String, Value) {
    let start = field
        .rfind("<!-- onetaskgraph.metadata")
        .expect("the field ends in a slot");
    let slot = &field[start + "<!-- onetaskgraph.metadata".len()..];
    let encoded = match slot.strip_prefix(" `") {
        Some(span) => span.trim_end().trim_end_matches("` -->"),
        None => slot
            .trim_start_matches('\n')
            .trim_end_matches("-->")
            .trim_end_matches('\\')
            .trim_end_matches('\n'),
    };
    (
        field[..start].to_owned(),
        serde_json::from_str(encoded).expect("the slot holds JSON"),
    )
}

#[test]
fn a_metadata_set_moves_only_the_slot_and_a_render_only_the_body_and_its_provenance_on_linear() {
    let sandbox = Sandbox::new();
    let (config, workspace) = slotted_workspace(&sandbox);
    let plan = folder(&sandbox, "plan", &[]);
    sandbox.project_document(&document(&json!({
        "linear": linear(&config, json!({})),
        "plan": markdown(&plan),
    })));

    for (verb, kind, id) in [
        ("task", "tasks", "I-M"),
        ("project", "projects", "LP-1"),
        ("document", "documents", "D-M"),
    ] {
        let before = workspace.long_form(kind, id).expect("held");
        let (above_before, slot_before) = split_slot(&before);
        let from = workspace.served().len();
        let answer = answered(
            &sandbox,
            &[
                "--json",
                verb,
                "metadata",
                "set",
                &format!("linear:{id}"),
                "myapp.review",
                r#"{"approved":true}"#,
            ],
        );
        assert_eq!(
            answer["value"],
            json!({"approved": true}),
            "{verb}: {answer}"
        );
        let after = workspace.long_form(kind, id).expect("held");
        let (above_after, slot_after) = split_slot(&after);
        assert_eq!(
            above_after, above_before,
            "{verb}: every byte above the slot"
        );
        let mut expected = slot_before.clone();
        expected["myapp.review"] = json!({"approved": true});
        assert_eq!(slot_after, expected, "{verb}: the slot gained one key");
        assert_eq!(
            mutations_since(&workspace, from).len(),
            1,
            "{verb}: one write"
        );

        // The same value again is a write that changes nothing, and sends none.
        let from = workspace.served().len();
        answered(
            &sandbox,
            &[
                "--json",
                verb,
                "metadata",
                "set",
                &format!("linear:{id}"),
                "myapp.review",
                r#"{"approved":true}"#,
            ],
        );
        assert_eq!(mutations_since(&workspace, from), Vec::<String>::new());
    }

    // A rendering replaces the body and the provenance together, and nothing else.
    let template = sandbox.subdirectory("templates").join("note.md");
    std::fs::write(&template, "A rendered body.\n").expect("a template");
    let template = template.to_string_lossy().into_owned();
    for (verb, kind, id) in [("task", "tasks", "I-M"), ("document", "documents", "D-M")] {
        let (_, slot_before) = split_slot(&workspace.long_form(kind, id).expect("held"));
        let regenerated = answered(
            &sandbox,
            &[
                "--json",
                verb,
                "render",
                &format!("linear:{id}"),
                "--template",
                &template,
                "--no-interactive",
            ],
        );
        assert_eq!(regenerated["changed"], true, "{verb}: {regenerated}");
        let after = workspace.long_form(kind, id).expect("held");
        let (above_after, slot_after) = split_slot(&after);
        assert_eq!(above_after, "A rendered body.\n\n\n", "{verb}: the body");
        let mut kept = slot_after.clone();
        let provenance = kept
            .as_object_mut()
            .expect("a slot")
            .remove("onetaskgraph.template")
            .expect("the provenance is recorded");
        assert_eq!(provenance["template"], json!(template), "{verb}");
        assert_eq!(kept, slot_before, "{verb}: every other slot entry kept");
    }

    // A copy out of Linear records where the item landed on the Linear item itself.
    let copied = answered(
        &sandbox,
        &["--json", "task", "copy", "linear:I-M", "--to", "plan"],
    );
    assert_eq!(copied["items"][0]["link"], "recorded", "{copied:#}");
    let (_, slot) = split_slot(&workspace.long_form("tasks", "I-M").expect("held"));
    assert_eq!(
        slot["onetaskgraph.copies"],
        json!({"plan": copied["items"][0]["destination"]})
    );
    // And the next copy follows it.
    let again = answered(
        &sandbox,
        &["--json", "task", "copy", "linear:I-M", "--to", "plan"],
    );
    assert_eq!(again["items"][0]["via"], "link", "{again:#}");
}

#[test]
fn a_linear_ticket_is_delivered_from_another_source_through_its_mapped_states() {
    let sandbox = Sandbox::new();
    let (config, workspace) = linear_workspace(
        &sandbox,
        held(
            vec![
                issue("L-T", "Todo", json!({})),
                issue("L-P", "Proposed", json!({})),
                issue("L-B", "Backlog", json!({})),
            ],
            Vec::new(),
            Vec::new(),
        ),
    );
    let plan = folder(
        &sandbox,
        "plan",
        &[
            (
                "tasks/D-1.md",
                "---\ntitle: Deliverer\nstatus: todo\n---\nbody\n",
            ),
            (
                "tasks/D-2.md",
                "---\ntitle: Idle deliverer\nstatus: todo\n---\nbody\n",
            ),
        ],
    );
    sandbox.project_document(&document(&json!({
        "linear": linear(&config, json!({"status_mapping": eng_mapping()})),
        "plan": markdown(&plan),
    })));

    // The relation is set on the deliverer, and the store keeps the ticket's own side in its
    // slot.
    answered(
        &sandbox,
        &[
            "--json",
            "task",
            "update",
            "plan:D-1",
            "--delivers",
            "linear:L-T",
        ],
    );
    assert_eq!(
        shown(&sandbox, "linear:L-T")["delivered_by"],
        json!(["plan:D-1"])
    );
    let (_, slot) = split_slot(&workspace.long_form("tasks", "L-T").expect("held"));
    assert_eq!(slot["onetaskgraph.delivered_by"], json!(["plan:D-1"]));

    for (deliverer, ticket) in [
        ("queued", "Queued"),
        ("in-progress", "In Progress"),
        ("done", "Done"),
    ] {
        let set = answered(
            &sandbox,
            &["--json", "task", "status", "set", "plan:D-1", deliverer],
        );
        assert_eq!(set["delivered"][0]["outcome"], "written", "{set:#}");
        assert_eq!(
            workspace.state_of("L-T").as_deref(),
            Some(ticket),
            "a {deliverer} deliverer"
        );
        assert_eq!(status(&sandbox, "linear:L-T"), json!([deliverer, ticket]));
    }

    // A ticket at `Proposed` or `Backlog` is left alone however its deliverer moves.
    answered(
        &sandbox,
        &[
            "--json",
            "task",
            "update",
            "plan:D-2",
            "--delivers",
            "linear:L-P",
            "--delivers",
            "linear:L-B",
        ],
    );
    let set = answered(
        &sandbox,
        &["--json", "task", "status", "set", "plan:D-2", "in-progress"],
    );
    assert_eq!(
        set["delivered"]
            .as_array()
            .expect("entries")
            .iter()
            .map(|entry| entry["outcome"].clone())
            .collect::<Vec<_>>(),
        [json!("left"), json!("left")],
        "{set:#}"
    );
    assert_eq!(workspace.state_of("L-P").as_deref(), Some("Proposed"));
    assert_eq!(workspace.state_of("L-B").as_deref(), Some("Backlog"));

    // A Linear task's own `delivers` is held in its slot under the reserved key.
    answered(
        &sandbox,
        &[
            "--json",
            "task",
            "update",
            "linear:L-P",
            "--delivers",
            "plan:D-2",
        ],
    );
    let (_, slot) = split_slot(&workspace.long_form("tasks", "L-P").expect("held"));
    assert_eq!(slot["onetaskgraph.delivers"], json!(["plan:D-2"]));
    assert_eq!(
        shown(&sandbox, "linear:L-P")["delivers"],
        json!(["plan:D-2"])
    );
}

/// The issues a follow-up search tells apart: one that matches every predicate, one whose
/// prose carries every searched phrase outside its slot, and one whose slot holds other values.
fn searched_workspace(sandbox: &Sandbox) -> (Value, LinearWorkspace) {
    let slot = |json: &str| format!("\n\n<!-- onetaskgraph.metadata\n{json}\n-->");
    let mut matching = issue(
        "S-MATCH",
        "Todo",
        json!({"title": "Alpha follow-up", "priority": "high"}),
    );
    matching["_linear_description"] = json!(format!(
        "The body.{}",
        slot(
            r#"{"caller.key":"v","onetaskgraph.origin":"plan:ORIG-1","orchestrator.follow-up":{"root_cause":"stale-cache"}}"#
        )
    ));
    let mut prose = issue(
        "S-PROSE",
        "Todo",
        json!({"title": "Second", "priority": "low"}),
    );
    prose["_linear_description"] = json!(
        "Quotes \"caller.key\":\"v\", \"onetaskgraph.origin\":\"plan:ORIG-1\" and \
         \"root_cause\":\"stale-cache\" in its prose, and the word zebra."
    );
    let mut other = issue(
        "S-OTHER",
        "Todo",
        json!({"title": "Third", "priority": "low"}),
    );
    other["_linear_description"] = json!(format!(
        "Another body.{}",
        slot(
            r#"{"caller.key":"w","onetaskgraph.origin":"plan:ORIG-2","orchestrator.follow-up":{"root_cause":"other"}}"#
        )
    ));
    // A slot in the multi-line spelling, spaced by hand: readable, and so a match.
    let mut legacy = issue("S-LEGACY", "Todo", json!({"title": "Fourth"}));
    legacy["_linear_description"] = json!(
        "Legacy body.\n\n<!-- onetaskgraph.metadata\n{\"caller.key\": \"v\", \
         \"onetaskgraph.origin\": \"plan:ORIG-1\"}\n-->"
    );
    let mut workspace = held(vec![matching, prose, other, legacy], Vec::new(), Vec::new());
    workspace["comments"] = json!([
        {"task": "S-MATCH", "comment": {"id": "C-1", "body": "recent",
            "created_at": "2026-09-01T00:00:00Z", "updated_at": "2026-10-01T12:00:00Z"}},
        {"task": "S-OTHER", "comment": {"id": "C-2", "body": "old",
            "created_at": "2026-09-01T00:00:00Z", "updated_at": "2026-09-01T00:00:00Z"}},
    ]);
    linear_workspace(sandbox, workspace)
}

#[test]
fn the_follow_up_searches_are_pushed_to_linear_and_return_exactly_what_matches() {
    let sandbox = Sandbox::new();
    let (config, workspace) = searched_workspace(&sandbox);
    let plan = folder(&sandbox, "plan", &[]);
    sandbox.project_document(&document(&json!({
        "linear": linear(&config, json!({})),
        "plan": markdown(&plan),
    })));
    for (arguments, predicate, expected) in [
        (
            vec!["--metadata", "caller.key=v"],
            "metadata",
            vec!["S-MATCH", "S-LEGACY"],
        ),
        (
            vec![
                "--metadata",
                "orchestrator.follow-up/root_cause=stale-cache",
            ],
            "metadata",
            vec!["S-MATCH"],
        ),
        (
            vec!["--origin", "plan:ORIG-1"],
            "origin",
            vec!["S-MATCH", "S-LEGACY"],
        ),
        (vec!["--priority", "high"], "priority", vec!["S-MATCH"]),
        (
            vec!["--commented-since", "2026-10-01T00:00:00Z"],
            "commented-since",
            vec!["S-MATCH"],
        ),
        (
            vec!["--search", "ALPHA", "--in", "title"],
            "search-title",
            vec!["S-MATCH"],
        ),
        (
            vec!["--search", "zebra", "--in", "content"],
            "search-content",
            vec!["S-PROSE"],
        ),
        (
            vec!["--search", "stale-cache", "--in", "content"],
            "search-content",
            vec!["S-PROSE"],
        ),
    ] {
        let mut full = vec!["--json", "task", "list", "--source", "linear"];
        full.extend_from_slice(&arguments);
        let from = workspace.served().len();
        let answer = answered(&sandbox, &full);
        assert_eq!(
            ids(&answer),
            expected
                .iter()
                .map(|id| format!("linear:{id}"))
                .collect::<Vec<_>>(),
            "{arguments:?}"
        );
        assert!(
            answer["plan"]["per_source"][0]["pushed_down"]
                .as_array()
                .expect("a plan")
                .contains(&json!(predicate)),
            "{arguments:?}: {:#}",
            answer["plan"]
        );
        // Linear was asked for the narrowing, not for the whole team.
        let filter = workspace
            .served()
            .into_iter()
            .skip(from)
            .find(|(query, _)| query == onetaskgraph_linear::graphql::ISSUES)
            .expect("one issue read")
            .1["filter"]
            .to_string();
        let member = match predicate {
            "metadata" | "origin" => "\"description\":{\"contains\"",
            "priority" => "\"priority\":{\"in\"",
            "commented-since" => "\"comments\":{\"some\"",
            "search-title" => "\"title\":{\"containsIgnoreCase\"",
            _ => "\"description\":{\"containsIgnoreCase\"",
        };
        assert!(filter.contains(member), "{arguments:?}: {filter}");
    }
}

#[test]
fn a_cross_source_edge_is_established_both_ways_and_never_taken_from_another_team_or_project() {
    for scope in [None, Some("LP-1")] {
        let sandbox = Sandbox::new();
        // A decoy in another team carries the far end's origin, and — for a scoped source —
        // so does one of this team filed in another project. Neither may stand for it. (To a
        // source with no `project`, an issue of its own team in any project is its own, so the
        // second decoy is only planted where it is one.)
        let decoy_slot =
            "Decoy.\n\n<!-- onetaskgraph.metadata\n{\"onetaskgraph.origin\":\"plan:F-1\"}\n-->";
        let mut other_team = issue("X-TEAM", "Todo", json!({"team": "OTHER"}));
        other_team["_linear_description"] = json!(decoy_slot);
        let mut other_project = issue("X-PROJECT", "Todo", json!({"project": "LP-2"}));
        other_project["_linear_description"] = json!(decoy_slot);
        let mut tasks = vec![
            other_team,
            issue("L-1", "Todo", json!({"project": "LP-1"})),
            issue("L-2", "Todo", json!({"project": "LP-1"})),
        ];
        if scope.is_some() {
            tasks.insert(1, other_project);
        }
        let (config, workspace) = linear_workspace(
            &sandbox,
            held(tasks, vec![project("LP-1"), project("LP-2")], Vec::new()),
        );
        let extra = scope.map_or_else(|| json!({}), |scope| json!({"project": scope}));
        let linear_source = linear(&config, extra);
        let plan = folder(
            &sandbox,
            "plan",
            &[
                (
                    "tasks/F-1.md",
                    "---\ntitle: Upstream\nstatus: todo\n---\nbody\n",
                ),
                (
                    "tasks/F-2.md",
                    "---\ntitle: Waits on upstream\nstatus: todo\ndepends_on: [F-1]\n---\nbody\n",
                ),
            ],
        );
        sandbox.project_document(&document(&json!({
            "linear": linear_source,
            "plan": markdown(&plan),
        })));
        // L-2 depends on L-1, natively.
        answered(
            &sandbox,
            &[
                "--json",
                "task",
                "update",
                "linear:L-2",
                "--depends-on",
                "linear:L-1",
            ],
        );

        // Linear → plan: a copy whose far end stayed behind records it, and the decoys
        // carrying that far end's origin are not taken for it.
        let copied = answered(
            &sandbox,
            &["--json", "task", "copy", "plan:F-2", "--to", "linear"],
        );
        let near = copied["items"][0]["destination"]
            .as_str()
            .expect("a destination")
            .to_owned();
        let far: Vec<Value> = answered(&sandbox, &["--json", "task", "deps", &near])["items"]
            .as_array()
            .expect("edges")
            .iter()
            .map(|edge| edge["to"]["id"].clone())
            .collect();
        assert_eq!(far, [json!("plan:F-1")], "{scope:?}");
        for decoy in ["X-TEAM", "X-PROJECT"] {
            assert!(
                !workspace
                    .long_form("tasks", near.split_once(':').expect("qualified").1)
                    .expect("held")
                    .contains(decoy),
                "{scope:?}: {decoy}"
            );
        }

        // plan → Linear: a copy out of Linear keeps its far end in Linear.
        let copied = answered(
            &sandbox,
            &["--json", "task", "copy", "linear:L-2", "--to", "plan"],
        );
        let near = copied["items"][0]["destination"]
            .as_str()
            .expect("a destination")
            .to_owned();
        let far: Vec<Value> = answered(&sandbox, &["--json", "task", "deps", &near])["items"]
            .as_array()
            .expect("edges")
            .iter()
            .map(|edge| edge["to"]["id"].clone())
            .collect();
        assert_eq!(far, [json!("linear:L-1")], "{scope:?}");

        // Once the far end itself is copied in, the next copy relates the two natively —
        // to the copy in this team and project, never to a decoy.
        let upstream = answered(
            &sandbox,
            &["--json", "task", "copy", "plan:F-1", "--to", "linear"],
        );
        let upstream = upstream["items"][0]["destination"].clone();
        let again = answered(
            &sandbox,
            &["--json", "task", "copy", "plan:F-2", "--to", "linear"],
        );
        let near = again["items"][0]["destination"]
            .as_str()
            .expect("a destination")
            .to_owned();
        let far: Vec<Value> = answered(&sandbox, &["--json", "task", "deps", &near])["items"]
            .as_array()
            .expect("edges")
            .iter()
            .map(|edge| edge["to"]["id"].clone())
            .collect();
        assert_eq!(far, [upstream], "{scope:?}");
    }
}