rightcommit 1.1.0

Self-hosted, Rust-built orchestration for Claude Code, Codex and Pi Agent. Parallel workflows, full control over every commit, and FinOps that shows exactly what each agent and model costs.
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
//! Run outputs are changes against the prepared sources, not a workspace listing.
use crate::{
    App,
    model::{Artifact, ArtifactFile, Run, id, now},
    store::private,
};
use anyhow::{Context, Result, ensure};
use rusqlite::params;
use sha2::{Digest, Sha256};
use std::{
    collections::BTreeMap,
    fs::File,
    io::{Read, Write},
    path::{Path, PathBuf},
};

const INLINE_PREVIEW_LIMIT: u64 = 1024 * 1024;

fn digest(path: &Path) -> Result<String> {
    let mut file = File::open(path)?;
    let mut hash = Sha256::new();
    let mut buffer = [0; 65536];
    loop {
        let n = file.read(&mut buffer)?;
        if n == 0 {
            break;
        }
        hash.update(&buffer[..n]);
    }
    Ok(hex::encode(hash.finalize()))
}

fn working_roots(app: &App, uid: i64, run: &Run) -> Result<Vec<PathBuf>> {
    let lineage = crate::subworkflows::ancestors(app, uid, run)?;
    let root = lineage.last().unwrap_or(run);
    let mut roots = vec![
        PathBuf::from(&run.workspace),
        app.data.join(format!("users/{uid}/workspaces/{}", root.id)),
    ];
    for (index, node) in root
        .workflow
        .nodes
        .iter()
        .filter(|n| n.kind == "Source")
        .enumerate()
    {
        let path = PathBuf::from(crate::source_access::source_path(root, index, node));
        roots.push(if path.is_absolute() {
            path
        } else {
            Path::new(&root.workspace).join(path)
        });
    }
    // Parents of a registered root are validated too; never traverse a link into
    // another user's files. Git's internal object store is not a workflow output.
    let data = std::fs::canonicalize(&app.data)?;
    let sources = std::fs::canonicalize(&app.sources).unwrap_or_else(|_| app.sources.clone());
    let mut canonical = Vec::new();
    for path in roots {
        if !path.exists() {
            continue;
        }
        ensure!(
            !path
                .ancestors()
                .take_while(|p| p.starts_with(&app.data)
                    || p.starts_with(&app.sources)
                    || p.starts_with(&data)
                    || p.starts_with(&sources))
                .any(|p| std::fs::symlink_metadata(p).is_ok_and(|m| m.is_symlink())),
            "Link nel percorso artefatti: {}",
            path.display()
        );
        let path = std::fs::canonicalize(path)?;
        ensure!(
            path.starts_with(&data) || path.starts_with(&sources),
            "Cartella artefatti esterna alle sorgenti della run"
        );
        if !canonical.contains(&path) {
            canonical.push(path);
        }
    }
    Ok(canonical)
}

fn inventory(app: &App, uid: i64, run: &Run) -> Result<BTreeMap<String, String>> {
    fn walk(path: &Path, files: &mut BTreeMap<String, String>) -> Result<()> {
        let meta = match std::fs::symlink_metadata(path) {
            Ok(meta) => meta,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
            Err(e) => return Err(e.into()),
        };
        if meta.is_symlink() {
            return Ok(());
        }
        if meta.is_dir() {
            if path.file_name().is_some_and(|n| n == ".git") {
                return Ok(());
            }
            for entry in std::fs::read_dir(path)? {
                walk(&entry?.path(), files)?;
            }
        } else if meta.is_file() {
            let key = path.to_string_lossy().into_owned();
            if let std::collections::btree_map::Entry::Vacant(e) = files.entry(key) {
                e.insert(
                    digest(path)
                        .with_context(|| format!("Lettura artefatto {}", path.display()))?,
                );
            }
        }
        Ok(())
    }
    let mut files = BTreeMap::new();
    for root in working_roots(app, uid, run)? {
        walk(&root, &mut files)?;
    }
    Ok(files)
}

pub fn baseline(app: &App, uid: i64, run: &Run) -> Result<()> {
    let exists: bool = app.store.db.lock().unwrap().query_row(
        "SELECT EXISTS(SELECT 1 FROM artifact_baselines WHERE user_id=? AND run=?)",
        params![uid, run.id],
        |r| r.get(0),
    )?;
    if !exists {
        let files = inventory(app, uid, run)?;
        app.store.db.lock().unwrap().execute(
            "INSERT OR IGNORE INTO artifact_baselines VALUES(?,?,?)",
            params![uid, run.id, serde_json::to_string(&files)?],
        )?;
    }
    Ok(())
}

pub(crate) fn blob_path(app: &App, uid: i64, hash: &str) -> Result<PathBuf> {
    ensure!(
        hash.len() == 64 && hash.bytes().all(|b| b.is_ascii_hexdigit()),
        "Impronta artefatto non valida"
    );
    Ok(app
        .data
        .join("system/artifact-files")
        .join(uid.to_string())
        .join(hash))
}

fn capture(app: &App, uid: i64, path: &Path) -> Result<(String, u64, Option<String>)> {
    let folder = app.data.join("system/artifact-files").join(uid.to_string());
    std::fs::create_dir_all(&folder)?;
    private(&folder, true)?;
    let temp = folder.join(format!("{}.tmp", id()));
    let result = (|| {
        let mut input = File::open(path)?;
        let mut output = std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&temp)?;
        private(&temp, false)?;
        let mut hash = Sha256::new();
        let mut size = 0u64;
        let mut buffer = [0; 65536];
        loop {
            let n = input.read(&mut buffer)?;
            if n == 0 {
                break;
            }
            output.write_all(&buffer[..n])?;
            hash.update(&buffer[..n]);
            size += n as u64;
        }
        output.flush()?;
        let hash = hex::encode(hash.finalize());
        let target = blob_path(app, uid, &hash)?;
        std::fs::rename(&temp, &target)?;
        let preview = if size <= INLINE_PREVIEW_LIMIT {
            std::fs::read_to_string(&target)
                .ok()
                .filter(|s| !s.contains('\0'))
        } else {
            None
        };
        Ok((hash, size, preview))
    })();
    if temp.exists() {
        let _ = std::fs::remove_file(temp);
    }
    result
}

fn description(
    app: &App,
    run: &Run,
    location: &str,
    change: &str,
    size: u64,
    preview: bool,
) -> (String, ArtifactFile) {
    let location_buf = std::fs::canonicalize(location).unwrap_or_else(|_| PathBuf::from(location));
    let location = location_buf.as_path();
    let sources = std::fs::canonicalize(&app.sources).unwrap_or_else(|_| app.sources.clone());
    let workspace =
        std::fs::canonicalize(&run.workspace).unwrap_or_else(|_| PathBuf::from(&run.workspace));
    let (root, path) = if let Ok(path) = location.strip_prefix(sources) {
        ("/sources", path.to_path_buf())
    } else {
        (
            "/data",
            location
                .strip_prefix(&workspace)
                .unwrap_or(location)
                .to_path_buf(),
        )
    };
    (
        path.to_string_lossy().into_owned(),
        ArtifactFile {
            modified: std::fs::metadata(location)
                .and_then(|m| m.modified())
                .ok()
                .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                .map_or(0, |d| d.as_millis() as u64),
            root: root.into(),
            location: location.to_string_lossy().into_owned(),
            change: change.into(),
            size,
            preview,
            blob: true,
        },
    )
}

/// Snapshot all changed files, including binary/large/hidden files, without a
/// catalog-size cap. Preview limits never limit discovery or download.
pub fn snapshot(
    app: &App,
    uid: i64,
    run: &Run,
    node: &str,
    binding: &str,
    summary: &str,
) -> Result<()> {
    baseline(app, uid, run)?;
    let raw: String = app.store.db.lock().unwrap().query_row(
        "SELECT json FROM artifact_baselines WHERE user_id=? AND run=?",
        params![uid, run.id],
        |r| r.get(0),
    )?;
    let initial: BTreeMap<String, String> = serde_json::from_str(&raw)?;
    let previous = app.store.artifacts(uid, &run.id)?;
    let previous_files: BTreeMap<_, _> = previous
        .iter()
        .filter_map(|artifact| {
            let info = file_info(app, uid, run, artifact);
            (info.change != "report").then_some((info.location, artifact))
        })
        .collect();
    let files = inventory(app, uid, run)?;
    let session = run.sessions.get(binding).cloned().unwrap_or_default();
    for (location, hash) in files {
        let prior = previous_files.get(&location).copied();
        if prior.is_some_and(|a| a.file.is_none()) && initial.get(&location) == Some(&hash) {
            continue;
        }
        if prior
            .map(|a| a.hash.as_str())
            .or_else(|| initial.get(&location).map(String::as_str))
            == Some(hash.as_str())
        {
            continue;
        }
        let (hash, size, preview) = capture(app, uid, Path::new(&location))?;
        let (path, file) = description(
            app,
            run,
            &location,
            if initial.contains_key(&location) {
                "modified"
            } else {
                "created"
            },
            size,
            preview.is_some(),
        );
        app.store.add_artifact(
            uid,
            &Artifact {
                id: id(),
                run: run.id.clone(),
                node: node.into(),
                path,
                version: prior.map_or(1, |a| a.version + 1),
                hash,
                content: preview.unwrap_or_default(),
                session: session.native_id.clone(),
                turn: session.turns,
                created: now(),
                file: Some(file),
            },
        )?;
    }
    if !summary.is_empty() {
        let path = format!(".nodo/reports/{node}.md");
        let prior = previous
            .iter()
            .rev()
            .find(|a| a.path == path && a.file.as_ref().is_none_or(|f| f.change == "report"));
        let lineage = crate::subworkflows::ancestors(app, uid, run)?;
        let root = lineage.last().unwrap_or(run);
        let location = app.data.join(format!(
            "users/{uid}/workspaces/{}/.nodo/reports/{node}.md",
            root.id
        ));
        app.store.add_artifact(
            uid,
            &Artifact {
                id: id(),
                run: run.id.clone(),
                node: node.into(),
                path,
                version: prior.map_or(1, |a| a.version + 1),
                hash: crate::store::hash(summary),
                content: summary.into(),
                session: session.native_id,
                turn: session.turns,
                created: now(),
                file: Some(ArtifactFile {
                    modified: now() as u64 * 1000,
                    root: "/data".into(),
                    location: location.to_string_lossy().into_owned(),
                    change: "report".into(),
                    size: summary.len() as u64,
                    preview: true,
                    blob: false,
                }),
            },
        )?;
    }
    Ok(())
}

/// Immutable download: never follow a mutable source path from artifact metadata.
pub fn download_path(app: &App, uid: i64, artifact: &Artifact) -> Result<Option<PathBuf>> {
    if artifact.file.as_ref().is_some_and(|f| f.blob) {
        Ok(Some(blob_path(app, uid, &artifact.hash)?))
    } else {
        Ok(None)
    }
}

pub fn cleanup(app: &App, uid: i64) -> Result<()> {
    let busy = app.busy.lock().unwrap();
    if !busy.is_empty() {
        return Ok(());
    }
    let folder = app.data.join("system/artifact-files").join(uid.to_string());
    if !folder.exists() {
        return Ok(());
    }
    let db = app.store.db.lock().unwrap();
    let mut q = db.prepare("SELECT json FROM artifacts WHERE user_id=?")?;
    let hashes = q
        .query_map([uid], |row| row.get::<_, String>(0))?
        .map(|row| {
            let a: Artifact = serde_json::from_str(&row?)?;
            Ok(a.hash)
        })
        .collect::<Result<std::collections::HashSet<_>>>()?;
    for entry in std::fs::read_dir(folder)? {
        let path = entry?.path();
        if path.extension().is_none()
            && !hashes.contains(&path.file_name().unwrap().to_string_lossy().into_owned())
        {
            std::fs::remove_file(path)?;
        }
    }
    Ok(())
}

/// The saved bytes are immutable. Read previews on demand so a personal limit
/// change also applies to files acquired before that preference existed.
pub(crate) fn read_text_preview(path: &Path, limit: u64) -> Result<Option<String>> {
    let file = File::open(path)?;
    if file.metadata()?.len() > limit {
        return Ok(None);
    }
    let mut bytes = Vec::new();
    file.take(limit.saturating_add(1)).read_to_end(&mut bytes)?;
    if bytes.len() as u64 > limit {
        return Ok(None);
    }
    Ok(String::from_utf8(bytes)
        .ok()
        .filter(|text| !text.contains('\0')))
}
pub(crate) fn text_preview(
    app: &App,
    uid: i64,
    artifact: &Artifact,
    limit: u64,
) -> Result<Option<String>> {
    if let Some(path) = download_path(app, uid, artifact)? {
        return read_text_preview(&path, limit);
    }
    Ok(
        (artifact.content.len() as u64 <= limit && !artifact.content.contains('\0'))
            .then(|| artifact.content.clone()),
    )
}

pub fn file_info(app: &App, uid: i64, run: &Run, artifact: &Artifact) -> ArtifactFile {
    if let Some(file) = &artifact.file {
        return file.clone();
    }
    let workspace =
        std::fs::canonicalize(&run.workspace).unwrap_or_else(|_| PathBuf::from(&run.workspace));
    let location = workspace.join(&artifact.path);
    let (_, mut info) = description(
        app,
        run,
        &location.to_string_lossy(),
        if artifact.path.starts_with(".nodo/reports/") {
            "report"
        } else {
            "legacy"
        },
        artifact.content.len() as u64,
        true,
    );
    info.blob = false;
    info.modified = artifact.created.max(0) as u64 * 1000;
    if info.change == "report" {
        info.root = "/data".into();
        info.location = app
            .data
            .join(format!(
                "users/{uid}/workspaces/{}/{}",
                run.id, artifact.path
            ))
            .to_string_lossy()
            .into_owned();
    }
    info
}

pub fn rebase(app: &App, uid: i64, old: &Run, new: &Run, artifact: &mut Artifact) {
    let Some(file) = &mut artifact.file else {
        return;
    };
    let location = PathBuf::from(&file.location);
    let mut mappings = vec![
        (
            app.data.join(format!("users/{uid}/workspaces/{}", old.id)),
            app.data.join(format!("users/{uid}/workspaces/{}", new.id)),
        ),
        (PathBuf::from(&old.workspace), PathBuf::from(&new.workspace)),
    ];
    for (index, node) in old
        .workflow
        .nodes
        .iter()
        .filter(|n| n.kind == "Source")
        .enumerate()
    {
        let from = PathBuf::from(crate::source_access::source_path(old, index, node));
        let from = if from.is_absolute() {
            from
        } else {
            Path::new(&old.workspace).join(from)
        };
        if let Some(next) = new.workflow.nodes.iter().find(|n| n.id == node.id) {
            let to = PathBuf::from(crate::source_access::source_path(new, index, next));
            mappings.push((
                from,
                if to.is_absolute() {
                    to
                } else {
                    Path::new(&new.workspace).join(to)
                },
            ));
        }
    }
    mappings.sort_by_key(|(from, _)| std::cmp::Reverse(from.components().count()));
    for (from, to) in mappings {
        let from = std::fs::canonicalize(&from).unwrap_or(from);
        let to = std::fs::canonicalize(&to).unwrap_or(to);
        if let Ok(relative) = location.strip_prefix(from) {
            let (path, mut info) = description(
                app,
                new,
                &to.join(relative).to_string_lossy(),
                &file.change,
                file.size,
                file.preview,
            );
            info.blob = file.blob;
            info.modified = file.modified;
            *file = info;
            artifact.path = path;
            break;
        }
    }
}

/// Backfill old runs once. Existing versions remain immutable; the current
/// workspace is explicitly recorded as recovered, with no invented node author.
pub fn recover_legacy_run(app: &App, uid: i64, run: &Run) -> Result<usize> {
    let recovered: bool = app.store.db.lock().unwrap().query_row(
        "SELECT EXISTS(SELECT 1 FROM artifact_recoveries WHERE user_id=? AND run=?)",
        params![uid, run.id],
        |r| r.get(0),
    )?;
    if recovered {
        return Ok(0);
    }
    ensure!(
        Path::new(&run.workspace).is_dir(),
        "Workspace storico non disponibile"
    );
    let previous = app.store.artifacts(uid, &run.id)?;
    let has_baseline: bool = app.store.db.lock().unwrap().query_row(
        "SELECT EXISTS(SELECT 1 FROM artifact_baselines WHERE user_id=? AND run=?)",
        params![uid, run.id],
        |r| r.get(0),
    )?;
    if !previous.iter().any(|a| a.file.is_none())
        && (has_baseline
            || !["completed", "failed", "interrupted", "stopped"].contains(&run.status.as_str()))
    {
        return Ok(0);
    }
    let latest: BTreeMap<_, _> = previous
        .iter()
        .filter_map(|a| {
            let info = file_info(app, uid, run, a);
            (info.change != "report").then_some((info.location, a))
        })
        .collect();
    let mut count = 0;
    for (location, hash) in inventory(app, uid, run)? {
        let prior = latest.get(&location).copied();
        if prior.is_some_and(|a| a.hash == hash) {
            continue;
        }
        let modified = std::fs::metadata(&location)?
            .modified()?
            .duration_since(std::time::UNIX_EPOCH)?
            .as_millis() as u64;
        // Missing snapshots may be inputs omitted by the former 1000-file cap.
        // Without an initial inventory, only discover files dated since this run
        // began. They are labelled recovered, never claimed as created by a node.
        if prior.is_none() && modified < run.created.max(0) as u64 * 1000 {
            continue;
        }
        let (hash, size, preview) = capture(app, uid, Path::new(&location))?;
        if prior.is_some_and(|a| a.hash == hash) {
            continue;
        }
        let (path, mut info) =
            description(app, run, &location, "recovered", size, preview.is_some());
        info.modified = modified;
        app.store.add_artifact(
            uid,
            &Artifact {
                id: id(),
                run: run.id.clone(),
                node: "artifact-recovery".into(),
                path,
                version: prior.map_or(1, |a| a.version + 1),
                hash,
                content: preview.unwrap_or_default(),
                session: String::new(),
                turn: 0,
                created: now(),
                file: Some(info),
            },
        )?;
        count += 1;
    }
    app.store.db.lock().unwrap().execute(
        "INSERT OR IGNORE INTO artifact_recoveries VALUES(?,?,?)",
        params![
            uid,
            run.id,
            serde_json::json!({"recovered":count,"at":now()}).to_string()
        ],
    )?;
    Ok(count)
}

pub fn recover_legacy_runs(app: &App) -> Result<(usize, usize)> {
    let runs: Vec<(i64, Run)> = {
        let db = app.store.db.lock().unwrap();
        let mut q=db.prepare("SELECT r.user_id,r.json FROM runs r WHERE (EXISTS(SELECT 1 FROM artifacts a WHERE a.user_id=r.user_id AND a.run=r.id AND json_extract(a.json,'$.file') IS NULL) OR (json_extract(r.json,'$.status') IN ('completed','failed','interrupted','stopped') AND NOT EXISTS(SELECT 1 FROM artifact_baselines b WHERE b.user_id=r.user_id AND b.run=r.id))) AND NOT EXISTS(SELECT 1 FROM artifact_recoveries b WHERE b.user_id=r.user_id AND b.run=r.id) ORDER BY r.rowid")?;
        q.query_map([], |row| {
            Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?))
        })?
        .map(|row| {
            let (uid, json) = row?;
            Ok((uid, serde_json::from_str(&json)?))
        })
        .collect::<Result<_>>()?
    };
    let mut completed = 0;
    let mut files = 0;
    for (uid, run) in runs {
        match recover_legacy_run(app, uid, &run) {
            Ok(count) => {
                completed += 1;
                files += count;
                tracing::info!(run=%run.id,recovered=count,"Artefatti storici recuperati");
            }
            Err(error) => {
                tracing::warn!(run=%run.id,%error,"Recupero artefatti storici non completato; verrà ritentato al riavvio")
            }
        }
    }
    Ok((completed, files))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::*;

    fn fixture(direct: bool) -> (tempfile::TempDir, App, Run, PathBuf, PathBuf) {
        let dir = tempfile::tempdir().unwrap();
        let app = crate::tests::app(dir.path());
        let rid = id();
        let run_folder = app.data.join(format!("users/1/workspaces/{rid}"));
        let workspace = if direct {
            app.sources.join("main")
        } else {
            run_folder.clone()
        };
        let second = app.sources.join("second");
        let copied = run_folder.join(".nodo/sources/copied");
        for p in [&workspace, &second, &copied] {
            std::fs::create_dir_all(p).unwrap();
            std::fs::write(p.join("original.txt"), "original").unwrap();
        }
        let mut context = BTreeMap::from([(
            "direct-source:second".into(),
            second.to_string_lossy().into_owned(),
        )]);
        if direct {
            context.insert("direct-primary".into(), "source".into());
            context.insert(
                "direct-source:source".into(),
                workspace.to_string_lossy().into_owned(),
            );
            context.insert(
                "source-path:copied".into(),
                copied.to_string_lossy().into_owned(),
            );
        }
        let workflow=serde_json::from_value(serde_json::json!({"id":"workflow","name":"Outputs","description":"","entry":"task","edges":[],"nodes":[
            {"id":"source","kind":"Source","source_type":"folder","source_mode":if direct {"direct"} else {"copy"},"location":"main"},
            {"id":"second","kind":"Source","source_type":"folder","source_mode":"direct","location":"second"},
            {"id":"copied","kind":"Source","source_type":"examples"},
            {"id":"task","kind":"Task"}]})).unwrap();
        let run = Run {
            id: rid,
            workflow,
            status: "paused".into(),
            current: "task".into(),
            created: now(),
            updated: now(),
            workspace: workspace.to_string_lossy().into_owned(),
            states: BTreeMap::new(),
            sessions: BTreeMap::new(),
            outputs: BTreeMap::new(),
            pending: None,
            active_edge: None,
            pause_requested: false,
            attempts: BTreeMap::new(),
            reworks: BTreeMap::new(),
            context,
            last_task: None,
            last_node: None,
            error: None,
            input: String::new(),
            execution: Default::default(),
            parent: None,
            children: vec![],
        };
        app.store.save_run(1, &run).unwrap();
        (dir, app, run, second, copied)
    }

    #[test]
    fn artifacts_only_changes_across_direct_copy_and_additional_sources() {
        for direct in [true, false] {
            let (_dir, app, run, second, copied) = fixture(direct);
            baseline(&app, 1, &run).unwrap();
            snapshot(&app, 1, &run, "task", "", "report").unwrap();
            assert_eq!(
                app.store.artifacts(1, &run.id).unwrap().len(),
                1,
                "Unchanged inputs are not artifacts"
            );
            let main = Path::new(&run.workspace);
            std::fs::write(main.join("original.txt"), "updated").unwrap();
            std::fs::write(main.join("new.txt"), "created").unwrap();
            std::fs::create_dir_all(main.join(".hidden")).unwrap();
            std::fs::write(main.join(".hidden/result.md"), "hidden result").unwrap();
            std::fs::write(second.join("original.txt"), "updated second").unwrap();
            std::fs::write(copied.join("binary.pdf"), b"%PDF\0\xffbinary").unwrap();
            let data_only = app
                .data
                .join(format!("users/1/workspaces/{}/output.zip", run.id));
            std::fs::write(&data_only, b"PK\0zip").unwrap();
            snapshot(&app, 1, &run, "task", "", "report 2").unwrap();
            let artifacts = app.store.artifacts(1, &run.id).unwrap();
            let files: Vec<_> = artifacts
                .iter()
                .filter(|a| a.file.as_ref().unwrap().change != "report")
                .collect();
            assert_eq!(files.len(), 6);
            assert!(files.iter().any(|a| a.path.contains(".hidden/result.md")));
            let main_change = files
                .iter()
                .find(|a| {
                    a.file.as_ref().unwrap().location
                        == std::fs::canonicalize(main.join("original.txt"))
                            .unwrap()
                            .to_string_lossy()
                })
                .unwrap();
            assert_eq!(
                main_change.file.as_ref().unwrap().root,
                if direct { "/sources" } else { "/data" }
            );
            assert_eq!(main_change.file.as_ref().unwrap().change, "modified");
            let pdf = files
                .iter()
                .find(|a| a.path.ends_with("binary.pdf"))
                .unwrap();
            assert!(!pdf.file.as_ref().unwrap().preview);
            assert_eq!(pdf.file.as_ref().unwrap().root, "/data");
            assert_eq!(
                std::fs::read(download_path(&app, 1, pdf).unwrap().unwrap()).unwrap(),
                b"%PDF\0\xffbinary"
            );
            std::fs::write(copied.join("binary.pdf"), "changed later").unwrap();
            // A stored version survives modifications and deletion of its working file.
            assert_eq!(
                std::fs::read(download_path(&app, 1, pdf).unwrap().unwrap()).unwrap(),
                b"%PDF\0\xffbinary"
            );
            std::fs::write(main.join("original.txt"), "original").unwrap();
            snapshot(&app, 1, &run, "next", "", "report").unwrap();
            let after = app.store.artifacts(1, &run.id).unwrap();
            let reverted = after
                .iter()
                .rev()
                .find(|a| a.path == main_change.path && a.file.as_ref().unwrap().change != "report")
                .unwrap();
            assert_eq!(reverted.version, 2);
            assert_eq!(reverted.content, "original");
            assert!(app.store.artifact(2, &pdf.id).is_err());
            assert!(blob_path(&app, 1, "../../outside").is_err());
        }
    }

    #[test]
    fn artifacts_large_binary_and_more_than_a_thousand_outputs_survive_restart() {
        let (_dir, app, run, _, _) = fixture(false);
        let root = Path::new(&run.workspace);
        for i in 0..1005 {
            std::fs::write(root.join(format!("input-{i}.txt")), "unchanged").unwrap();
        }
        baseline(&app, 1, &run).unwrap();
        for i in 0..1005 {
            std::fs::write(root.join(format!("output-{i}.txt")), "output").unwrap();
        }
        let large = vec![b'x'; 1024 * 1024 + 1];
        std::fs::write(root.join("large.txt"), &large).unwrap();
        let reopened = crate::tests::app(&app.data);
        snapshot(&reopened, 1, &run, "task", "", "").unwrap();
        let artifacts = reopened.store.artifacts(1, &run.id).unwrap();
        assert_eq!(artifacts.len(), 1006);
        let large_artifact = artifacts.iter().find(|a| a.path == "large.txt").unwrap();
        assert!(!large_artifact.file.as_ref().unwrap().preview);
        assert_eq!(
            std::fs::read(
                download_path(&reopened, 1, large_artifact)
                    .unwrap()
                    .unwrap()
            )
            .unwrap(),
            large
        );
        snapshot(&reopened, 1, &run, "next", "", "").unwrap();
        assert_eq!(reopened.store.artifacts(1, &run.id).unwrap().len(), 1006);
    }

    #[test]
    fn artifacts_legacy_resume_keeps_history_and_filters_only_changes_after_resume() {
        let (_dir, app, run, _, _) = fixture(false);
        let original = Path::new(&run.workspace).join("original.txt");
        let legacy = Artifact {
            id: id(),
            run: run.id.clone(),
            node: "old".into(),
            path: "original.txt".into(),
            version: 4,
            hash: crate::store::hash("old snapshot"),
            content: "old snapshot".into(),
            session: String::new(),
            turn: 1,
            created: 1,
            file: None,
        };
        app.store.add_artifact(1, &legacy).unwrap();
        baseline(&app, 1, &run).unwrap();
        snapshot(&app, 1, &run, "task", "", "").unwrap();
        assert_eq!(app.store.artifacts(1, &run.id).unwrap().len(), 1);
        let info = file_info(&app, 1, &run, &legacy);
        assert_eq!(info.change, "legacy");
        assert_eq!(info.modified, 1000);
        std::fs::write(original, "after resume").unwrap();
        snapshot(&app, 1, &run, "task", "", "").unwrap();
        let artifacts = app.store.artifacts(1, &run.id).unwrap();
        assert_eq!(artifacts.len(), 2);
        assert_eq!(artifacts[1].version, 5);
        assert_eq!(artifacts[1].content, "after resume");
    }

    #[test]
    fn artifacts_inherited_from_direct_run_point_to_new_copy_but_keep_downloads() {
        let (_dir, app, run, _, _) = fixture(true);
        baseline(&app, 1, &run).unwrap();
        std::fs::write(Path::new(&run.workspace).join("output.txt"), "output").unwrap();
        snapshot(&app, 1, &run, "task", "", "").unwrap();
        let mut artifact = app.store.artifacts(1, &run.id).unwrap().remove(0);
        let mut new = run.clone();
        new.id = id();
        let dest = app.data.join(format!("users/1/workspaces/{}", new.id));
        std::fs::create_dir_all(&dest).unwrap();
        std::fs::write(dest.join("output.txt"), "output").unwrap();
        new.workspace = dest.to_string_lossy().into_owned();
        new.context.clear();
        let old_modified = artifact.file.as_ref().unwrap().modified;
        rebase(&app, 1, &run, &new, &mut artifact);
        let info = artifact.file.as_ref().unwrap();
        assert_eq!(info.root, "/data");
        assert_eq!(artifact.path, "output.txt");
        assert_eq!(info.modified, old_modified);
        assert_eq!(
            std::fs::read(download_path(&app, 1, &artifact).unwrap().unwrap()).unwrap(),
            b"output"
        );
    }

    #[test]
    fn artifacts_legacy_recovery_preserves_versions_discovers_outputs_and_is_idempotent() {
        for direct in [true, false] {
            let (_dir, app, mut run, _, copied) = fixture(direct);
            run.created = now() - 60;
            run.updated = now();
            app.store.save_run(1, &run).unwrap();
            let root = Path::new(&run.workspace);
            let old =
                std::time::UNIX_EPOCH + std::time::Duration::from_secs((run.created - 10) as u64);
            for location in inventory(&app, 1, &run).unwrap().keys() {
                File::options()
                    .write(true)
                    .open(location)
                    .unwrap()
                    .set_times(std::fs::FileTimes::new().set_modified(old))
                    .unwrap();
            }
            let original = Artifact {
                id: id(),
                run: run.id.clone(),
                node: "task".into(),
                path: "original.txt".into(),
                version: 3,
                hash: crate::store::hash("original"),
                content: "original".into(),
                session: "original-session".into(),
                turn: 1,
                created: run.created,
                file: None,
            };
            app.store.add_artifact(1, &original).unwrap();
            std::fs::write(root.join("original.txt"), "updated document").unwrap();
            std::fs::write(root.join("missing-report.md"), "# Recovered report").unwrap();
            std::fs::write(copied.join("missing-binary.pdf"), b"%PDF\0\xff").unwrap();
            let expected_modified = std::fs::metadata(root.join("original.txt"))
                .unwrap()
                .modified()
                .unwrap()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_millis() as u64;
            let (runs, files) = recover_legacy_runs(&app).unwrap();
            assert_eq!(runs, 1);
            assert_eq!(files, 3);
            let artifacts = app.store.artifacts(1, &run.id).unwrap();
            assert_eq!(artifacts.len(), 4);
            assert_eq!(
                app.store.artifact(1, &original.id).unwrap().content,
                "original"
            );
            assert!(app.store.artifact(1, &original.id).unwrap().file.is_none());
            let updated = artifacts.iter().find(|a| a.version == 4).unwrap();
            assert_eq!(updated.content, "updated document");
            let info = updated.file.as_ref().unwrap();
            assert_eq!(info.change, "recovered");
            assert_eq!(info.modified, expected_modified);
            assert_eq!(info.root, if direct { "/sources" } else { "/data" });
            let pdf = artifacts
                .iter()
                .find(|a| a.path.ends_with("missing-binary.pdf"))
                .unwrap();
            assert_eq!(
                std::fs::read(download_path(&app, 1, pdf).unwrap().unwrap()).unwrap(),
                b"%PDF\0\xff"
            );
            assert!(
                !artifacts
                    .iter()
                    .any(|a| a.path.ends_with("copied/original.txt"))
            );
            assert_eq!(recover_legacy_runs(&app).unwrap(), (0, 0));
            let reopened = crate::tests::app(&app.data);
            assert_eq!(recover_legacy_runs(&reopened).unwrap(), (0, 0));
            assert_eq!(app.store.artifacts(1, &run.id).unwrap().len(), 4);
        }
    }

    #[test]
    fn artifacts_recovery_includes_old_failed_runs_that_never_saved_a_snapshot() {
        let (_dir, app, mut run, _, _) = fixture(false);
        run.created = now() - 60;
        run.status = "failed".into();
        app.store.save_run(1, &run).unwrap();
        let old = std::time::UNIX_EPOCH + std::time::Duration::from_secs((run.created - 10) as u64);
        for location in inventory(&app, 1, &run).unwrap().keys() {
            File::options()
                .write(true)
                .open(location)
                .unwrap()
                .set_times(std::fs::FileTimes::new().set_modified(old))
                .unwrap();
        }
        std::fs::write(
            Path::new(&run.workspace).join("partial-result.txt"),
            "partial output",
        )
        .unwrap();
        assert_eq!(recover_legacy_runs(&app).unwrap(), (1, 1));
        let files = app.store.artifacts(1, &run.id).unwrap();
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].path, "partial-result.txt");
    }

    #[test]
    fn artifacts_recovery_skips_new_runs_and_unavailable_workspaces_without_losing_history() {
        let (_dir, app, run, _, _) = fixture(false);
        baseline(&app, 1, &run).unwrap();
        std::fs::write(Path::new(&run.workspace).join("new.txt"), "new").unwrap();
        snapshot(&app, 1, &run, "task", "", "").unwrap();
        assert_eq!(recover_legacy_runs(&app).unwrap(), (0, 0));
        let original = Artifact {
            id: id(),
            run: run.id.clone(),
            node: "task".into(),
            path: "original.txt".into(),
            version: 1,
            hash: crate::store::hash("original"),
            content: "original".into(),
            session: String::new(),
            turn: 1,
            created: 1,
            file: None,
        };
        app.store.add_artifact(1, &original).unwrap();
        std::fs::remove_dir_all(&run.workspace).unwrap();
        assert_eq!(recover_legacy_runs(&app).unwrap(), (0, 0));
        assert_eq!(
            app.store.artifact(1, &original.id).unwrap().content,
            "original"
        );
    }

    #[test]
    fn artifact_preview_limit_changes_apply_to_existing_immutable_files() {
        let (_dir, app, run, _, _) = fixture(false);
        baseline(&app, 1, &run).unwrap();
        let path = Path::new(&run.workspace).join("large.txt");
        std::fs::write(&path, vec![b'x'; 2_000_000]).unwrap();
        snapshot(&app, 1, &run, "task", "", "").unwrap();
        let artifact = app.store.artifacts(1, &run.id).unwrap().remove(0);
        assert!(!artifact.file.as_ref().unwrap().preview);
        assert_eq!(
            text_preview(
                &app,
                1,
                &artifact,
                app.store
                    .settings(1)
                    .unwrap()
                    .file_preview_limit_bytes()
                    .unwrap()
            )
            .unwrap()
            .unwrap()
            .len(),
            2_000_000
        );
        let mut settings = app.store.settings(1).unwrap();
        settings.file_preview_limit_mb = 1;
        app.store.save_settings(1, &settings).unwrap();
        assert!(
            text_preview(
                &app,
                1,
                &artifact,
                settings.file_preview_limit_bytes().unwrap()
            )
            .unwrap()
            .is_none()
        );
        settings.file_preview_limit_mb = 3;
        app.store.save_settings(1, &settings).unwrap();
        std::fs::write(path, "changed working file").unwrap();
        assert_eq!(
            text_preview(
                &app,
                1,
                &artifact,
                settings.file_preview_limit_bytes().unwrap()
            )
            .unwrap()
            .unwrap()
            .len(),
            2_000_000
        );
        assert_eq!(
            app.store.artifact(1, &artifact.id).unwrap().hash,
            artifact.hash
        );
    }

    #[test]
    fn artifacts_ignore_symlink_escapes_and_git_metadata() {
        let (dir, app, run, _, _) = fixture(false);
        baseline(&app, 1, &run).unwrap();
        let root = Path::new(&run.workspace);
        let secret = dir.path().join("private-secret");
        std::fs::write(&secret, "secret").unwrap();
        std::os::unix::fs::symlink(&secret, root.join("escape.txt")).unwrap();
        std::fs::create_dir_all(root.join(".git")).unwrap();
        std::fs::write(root.join(".git/internal"), "git").unwrap();
        snapshot(&app, 1, &run, "task", "", "").unwrap();
        assert!(app.store.artifacts(1, &run.id).unwrap().is_empty());
    }
}