apoc 0.9.1

Agentic process control for LLMs
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
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};

use base64::Engine as _;
use rusqlite::hooks::{AuthAction, AuthContext, Authorization};
use rusqlite::types::{Value as SqlValue, ValueRef};
use rusqlite::{Connection, OpenFlags, TransactionBehavior, params_from_iter};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};

use crate::model::now_ms;
use crate::store::state_dir;

use super::DebuggerManager;

pub const LEGACY_DEBUGGER_INDEX: &str = "debugger-legacy.sqlite";

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct LegacyDebuggerTableMigration {
    pub name: String,
    pub rows: u64,
    pub source_digest: String,
    pub sanitized_source_digest: String,
    pub target_digest: String,
    pub sanitized_columns: Vec<String>,
    pub sanitized_values: u64,
    pub matched: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct LegacyDebuggerArtifactMigration {
    pub source: String,
    pub kind: String,
    pub media_type: String,
    pub bytes: u64,
    pub source_digest: String,
    pub artifact_id: String,
    pub artifact_path: String,
    pub target_digest: String,
    pub matched: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct LegacyDebuggerMigration {
    pub source: String,
    pub index: String,
    pub backup: Option<String>,
    pub tables: Vec<LegacyDebuggerTableMigration>,
    pub total_rows: u64,
    pub source_digest: String,
    pub sanitized_source_digest: String,
    pub target_digest: String,
    pub sanitized_values: u64,
    pub matched: bool,
    #[serde(default)]
    pub artifacts: Vec<LegacyDebuggerArtifactMigration>,
    #[serde(default)]
    pub artifact_files: u64,
    #[serde(default)]
    pub artifact_bytes: u64,
    #[serde(default)]
    pub artifact_source_digest: String,
    #[serde(default)]
    pub artifact_target_digest: String,
    #[serde(default = "default_true")]
    pub artifacts_matched: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct LegacyDebuggerQuery {
    pub index: String,
    pub columns: Vec<String>,
    pub rows: Vec<BTreeMap<String, Value>>,
    pub truncated: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct LegacyDebuggerIndexStatus {
    pub index: String,
    pub exists: bool,
    pub bytes: Option<u64>,
    pub tables: usize,
    pub rows: u64,
    pub digest: Option<String>,
}

struct StagedLegacyDebuggerMigration {
    tables: Vec<LegacyDebuggerTableMigration>,
    total_rows: u64,
    source_digest: String,
    sanitized_source_digest: String,
    target_digest: String,
    sanitized_values: u64,
}

pub fn default_legacy_debugger_index() -> Result<PathBuf, String> {
    Ok(state_dir()?.join(LEGACY_DEBUGGER_INDEX))
}

pub fn migrate_legacy_debugger(
    source: &Path,
    index: Option<&Path>,
    replace: bool,
) -> Result<LegacyDebuggerMigration, String> {
    if !source.is_file() {
        return Err(format!(
            "legacy dbg database does not exist: {}",
            source.display()
        ));
    }
    let index = index
        .map(Path::to_path_buf)
        .map_or_else(default_legacy_debugger_index, Ok)?;
    if source == index {
        return Err("legacy source and sanitized index must differ".to_string());
    }
    if index.exists() && !replace {
        return Err(format!(
            "sanitized debugger index already exists: {}; pass replace to migrate again",
            index.display()
        ));
    }
    if let Some(parent) = index.parent() {
        std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
    }
    let staging = index.with_extension(format!("sqlite.{}.tmp", uuid::Uuid::now_v7()));
    let result = migrate_to_staging(source, &staging);
    let staged = match result {
        Ok(result) => result,
        Err(error) => {
            let _ = std::fs::remove_file(&staging);
            return Err(error);
        }
    };
    let backup = if index.exists() {
        let backup = index.with_extension(format!("sqlite.backup-{}", now_ms()));
        std::fs::rename(&index, &backup).map_err(|error| error.to_string())?;
        Some(backup)
    } else {
        None
    };
    if let Err(error) = std::fs::rename(&staging, &index) {
        if let Some(backup) = &backup {
            let _ = std::fs::rename(backup, &index);
        }
        return Err(error.to_string());
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&index, std::fs::Permissions::from_mode(0o600))
            .map_err(|error| error.to_string())?;
    }
    Ok(LegacyDebuggerMigration {
        source: source.display().to_string(),
        index: index.display().to_string(),
        backup: backup.map(|path| path.display().to_string()),
        matched: staged.sanitized_source_digest == staged.target_digest,
        tables: staged.tables,
        total_rows: staged.total_rows,
        source_digest: staged.source_digest,
        sanitized_source_digest: staged.sanitized_source_digest,
        target_digest: staged.target_digest,
        sanitized_values: staged.sanitized_values,
        artifacts: Vec::new(),
        artifact_files: 0,
        artifact_bytes: 0,
        artifact_source_digest: empty_digest(),
        artifact_target_digest: empty_digest(),
        artifacts_matched: true,
    })
}

impl DebuggerManager {
    pub fn import_legacy_debugger_artifacts(
        &self,
        sources: &[PathBuf],
    ) -> Result<Vec<LegacyDebuggerArtifactMigration>, String> {
        let mut files = BTreeSet::new();
        for source in sources {
            collect_artifact_files(source, &mut files)?;
        }
        files
            .into_iter()
            .map(|source| {
                let (source_digest, bytes) = digest_file(&source)?;
                let (kind, media_type) = legacy_artifact_type(&source);
                let artifact = self.store.put_debugger_artifact_file(
                    "legacy-debugger-import",
                    None,
                    kind,
                    media_type,
                    &source,
                )?;
                let (target_digest, target_bytes) = digest_file(Path::new(&artifact.path))?;
                Ok(LegacyDebuggerArtifactMigration {
                    source: source.display().to_string(),
                    kind: kind.to_string(),
                    media_type: media_type.to_string(),
                    bytes,
                    source_digest: source_digest.clone(),
                    artifact_id: artifact.id,
                    artifact_path: artifact.path,
                    target_digest: target_digest.clone(),
                    matched: source_digest == target_digest && bytes == target_bytes,
                })
            })
            .collect()
    }
}

pub fn validate_legacy_debugger_artifacts(sources: &[PathBuf]) -> Result<(), String> {
    let mut files = BTreeSet::new();
    for source in sources {
        collect_artifact_files(source, &mut files)?;
    }
    for file in files {
        digest_file(&file)?;
    }
    Ok(())
}

pub fn attach_legacy_artifact_summary(
    migration: &mut LegacyDebuggerMigration,
    artifacts: Vec<LegacyDebuggerArtifactMigration>,
) {
    let mut source = Sha256::new();
    let mut target = Sha256::new();
    for artifact in &artifacts {
        update_artifact_aggregate(&mut source, &artifact.source, &artifact.source_digest);
        update_artifact_aggregate(&mut target, &artifact.source, &artifact.target_digest);
    }
    migration.artifact_files = artifacts.len() as u64;
    migration.artifact_bytes = artifacts.iter().map(|artifact| artifact.bytes).sum();
    migration.artifact_source_digest = format!("{:x}", source.finalize());
    migration.artifact_target_digest = format!("{:x}", target.finalize());
    migration.artifacts_matched = artifacts.iter().all(|artifact| artifact.matched)
        && migration.artifact_source_digest == migration.artifact_target_digest;
    migration.artifacts = artifacts;
}

fn collect_artifact_files(path: &Path, files: &mut BTreeSet<PathBuf>) -> Result<(), String> {
    let metadata = std::fs::symlink_metadata(path).map_err(|error| {
        format!(
            "legacy debugger artifact does not exist: {}: {error}",
            path.display()
        )
    })?;
    if metadata.file_type().is_symlink() {
        return Err(format!(
            "legacy debugger artifact symlinks are not followed: {}",
            path.display()
        ));
    }
    if metadata.is_file() {
        files.insert(path.canonicalize().map_err(|error| error.to_string())?);
        return Ok(());
    }
    if !metadata.is_dir() {
        return Err(format!(
            "legacy debugger artifact is not a regular file or directory: {}",
            path.display()
        ));
    }
    let mut children = std::fs::read_dir(path)
        .map_err(|error| error.to_string())?
        .map(|entry| {
            entry
                .map(|entry| entry.path())
                .map_err(|error| error.to_string())
        })
        .collect::<Result<Vec<_>, _>>()?;
    children.sort();
    for child in children {
        collect_artifact_files(&child, files)?;
    }
    Ok(())
}

fn digest_file(path: &Path) -> Result<(String, u64), String> {
    use std::io::Read as _;

    let mut file = std::fs::File::open(path).map_err(|error| error.to_string())?;
    let mut digest = Sha256::new();
    let mut bytes = 0_u64;
    let mut buffer = [0_u8; 64 * 1024];
    loop {
        let read = file.read(&mut buffer).map_err(|error| error.to_string())?;
        if read == 0 {
            break;
        }
        digest.update(&buffer[..read]);
        bytes = bytes.saturating_add(read as u64);
    }
    Ok((format!("{:x}", digest.finalize()), bytes))
}

fn legacy_artifact_type(path: &Path) -> (&'static str, &'static str) {
    let extension = path
        .extension()
        .and_then(|value| value.to_str())
        .unwrap_or_default()
        .to_ascii_lowercase();
    let name = path
        .file_name()
        .and_then(|value| value.to_str())
        .unwrap_or_default()
        .to_ascii_lowercase();
    match extension.as_str() {
        "png" => ("legacy_image", "image/png"),
        "jpg" | "jpeg" => ("legacy_image", "image/jpeg"),
        "webp" => ("legacy_image", "image/webp"),
        "html" | "htm" => ("legacy_report", "text/html"),
        "jsonl" | "ndjson" => ("legacy_trace", "application/x-ndjson"),
        "json" if name.contains("record") => ("legacy_recording", "application/json"),
        "json" => ("legacy_trace", "application/json"),
        "zip" => ("legacy_bundle", "application/zip"),
        "tar" => ("legacy_bundle", "application/x-tar"),
        "bundle" => ("legacy_bundle", "application/octet-stream"),
        _ if name.contains("record") => ("legacy_recording", "application/octet-stream"),
        _ if name.contains("trace") => ("legacy_trace", "application/octet-stream"),
        _ => ("legacy_artifact", "application/octet-stream"),
    }
}

fn update_artifact_aggregate(digest: &mut Sha256, source: &str, content_digest: &str) {
    digest.update((source.len() as u64).to_le_bytes());
    digest.update(source.as_bytes());
    digest.update(content_digest.as_bytes());
}

fn empty_digest() -> String {
    format!("{:x}", Sha256::digest([]))
}

fn default_true() -> bool {
    true
}

pub fn query_legacy_debugger(
    index: Option<&Path>,
    sql: &str,
    limit: usize,
) -> Result<LegacyDebuggerQuery, String> {
    let index = index
        .map(Path::to_path_buf)
        .map_or_else(default_legacy_debugger_index, Ok)?;
    if !index.is_file() {
        return Err(format!(
            "sanitized debugger index does not exist: {}",
            index.display()
        ));
    }
    let sql = sql.trim();
    let lower = sql.to_ascii_lowercase();
    if sql.is_empty()
        || sql.contains(';')
        || !(lower.starts_with("select ") || lower.starts_with("with "))
    {
        return Err("legacy debugger query must be one SELECT or WITH statement".to_string());
    }
    let limit = limit.clamp(1, 1_000);
    let connection = Connection::open_with_flags(
        &index,
        OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
    )
    .map_err(|error| error.to_string())?;
    connection
        .execute_batch("PRAGMA query_only=ON; PRAGMA trusted_schema=OFF;")
        .map_err(|error| error.to_string())?;
    connection
        .authorizer(Some(authorize_legacy_query))
        .map_err(|error| error.to_string())?;
    let wrapped = format!("SELECT * FROM ({sql}) LIMIT {}", limit + 1);
    let mut statement = connection
        .prepare(&wrapped)
        .map_err(|error| error.to_string())?;
    let columns = statement
        .column_names()
        .into_iter()
        .map(str::to_string)
        .collect::<Vec<_>>();
    let mut query = statement.query([]).map_err(|error| error.to_string())?;
    let mut rows = Vec::new();
    while let Some(row) = query.next().map_err(|error| error.to_string())? {
        let mut output = BTreeMap::new();
        for (index, column) in columns.iter().enumerate() {
            output.insert(
                column.clone(),
                value_ref_json(row.get_ref(index).map_err(|error| error.to_string())?),
            );
        }
        rows.push(output);
    }
    let truncated = rows.len() > limit;
    rows.truncate(limit);
    Ok(LegacyDebuggerQuery {
        index: index.display().to_string(),
        columns,
        rows,
        truncated,
    })
}

fn authorize_legacy_query(context: AuthContext<'_>) -> Authorization {
    match context.action {
        AuthAction::Read { .. }
        | AuthAction::Select
        | AuthAction::Function { .. }
        | AuthAction::Recursive => Authorization::Allow,
        _ => Authorization::Deny,
    }
}

pub fn legacy_debugger_status(index: Option<&Path>) -> Result<LegacyDebuggerIndexStatus, String> {
    let index = index
        .map(Path::to_path_buf)
        .map_or_else(default_legacy_debugger_index, Ok)?;
    if !index.is_file() {
        return Ok(LegacyDebuggerIndexStatus {
            index: index.display().to_string(),
            exists: false,
            bytes: None,
            tables: 0,
            rows: 0,
            digest: None,
        });
    }
    let connection = Connection::open_with_flags(
        &index,
        OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
    )
    .map_err(|error| error.to_string())?;
    let tables = user_tables(&connection)?;
    let (rows, digest) = database_digest(&connection, &tables)?;
    Ok(LegacyDebuggerIndexStatus {
        index: index.display().to_string(),
        exists: true,
        bytes: std::fs::metadata(&index)
            .ok()
            .map(|metadata| metadata.len()),
        tables: tables.len(),
        rows,
        digest: Some(digest),
    })
}

fn migrate_to_staging(
    source: &Path,
    staging: &Path,
) -> Result<StagedLegacyDebuggerMigration, String> {
    let source_connection = Connection::open_with_flags(
        source,
        OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
    )
    .map_err(|error| error.to_string())?;
    let tables = user_tables(&source_connection)?;
    let mut target = Connection::open(staging).map_err(|error| error.to_string())?;
    let transaction = target
        .transaction_with_behavior(TransactionBehavior::Immediate)
        .map_err(|error| error.to_string())?;
    let mut sensitive_by_table = BTreeMap::new();
    let mut sanitized_values_by_table = BTreeMap::new();
    for table in &tables {
        let (sensitive, sanitized_values) =
            copy_sanitized_table(&source_connection, &transaction, table)?;
        sensitive_by_table.insert(table.clone(), sensitive);
        sanitized_values_by_table.insert(table.clone(), sanitized_values);
    }
    transaction.commit().map_err(|error| error.to_string())?;

    let mut migrated = Vec::new();
    let mut total_rows = 0;
    let mut total_sanitized_values = 0;
    for table in &tables {
        let (source_rows, source_digest) = table_digest(&source_connection, table)?;
        let sensitive = sensitive_by_table
            .get(table)
            .ok_or_else(|| format!("missing sanitization plan for legacy table {table}"))?;
        let (_, sanitized_source_digest) =
            table_digest_with_sanitization(&source_connection, table, sensitive)?;
        let (target_rows, target_digest) = table_digest(&target, table)?;
        if source_rows != target_rows {
            return Err(format!(
                "legacy table {table} row count changed from {source_rows} to {target_rows}"
            ));
        }
        total_rows += source_rows;
        let sanitized_values = *sanitized_values_by_table.get(table).unwrap_or(&0);
        total_sanitized_values += sanitized_values;
        migrated.push(LegacyDebuggerTableMigration {
            name: table.clone(),
            rows: source_rows,
            matched: sanitized_source_digest == target_digest,
            source_digest,
            sanitized_source_digest,
            target_digest,
            sanitized_columns: sensitive.iter().cloned().collect(),
            sanitized_values,
        });
    }
    let (_, source_digest) = database_digest(&source_connection, &tables)?;
    let sanitized_source_digest = database_digest_from_tables(
        migrated
            .iter()
            .map(|table| (&table.name, table.rows, &table.sanitized_source_digest)),
    );
    let (_, target_digest) = database_digest(&target, &tables)?;
    if sanitized_source_digest != target_digest || migrated.iter().any(|table| !table.matched) {
        return Err("legacy debugger migration digest mismatch".to_string());
    }
    Ok(StagedLegacyDebuggerMigration {
        tables: migrated,
        total_rows,
        source_digest,
        sanitized_source_digest,
        target_digest,
        sanitized_values: total_sanitized_values,
    })
}

fn user_tables(connection: &Connection) -> Result<Vec<String>, String> {
    let mut statement = connection
        .prepare(
            "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name",
        )
        .map_err(|error| error.to_string())?;
    let rows = statement
        .query_map([], |row| row.get::<_, String>(0))
        .map_err(|error| error.to_string())?;
    rows.collect::<Result<Vec<_>, _>>()
        .map_err(|error| error.to_string())
}

fn copy_sanitized_table(
    source: &Connection,
    target: &rusqlite::Transaction<'_>,
    table: &str,
) -> Result<(BTreeSet<String>, u64), String> {
    let columns = table_columns(source, table)?;
    if columns.is_empty() {
        return Err(format!("legacy table {table} has no columns"));
    }
    let sensitive = columns
        .iter()
        .filter(|column| !legacy_query_column_is_safe(&column.name))
        .map(|column| column.name.clone())
        .collect::<BTreeSet<_>>();
    let definition = columns
        .iter()
        .map(|column| format!("{} {}", quote_identifier(&column.name), column.affinity))
        .collect::<Vec<_>>()
        .join(", ");
    target
        .execute_batch(&format!(
            "CREATE TABLE {} ({definition})",
            quote_identifier(table)
        ))
        .map_err(|error| format!("could not create sanitized table {table}: {error}"))?;

    let mut source_statement = source
        .prepare(&format!("SELECT * FROM {}", quote_identifier(table)))
        .map_err(|error| error.to_string())?;
    let placeholders = (1..=columns.len())
        .map(|index| format!("?{index}"))
        .collect::<Vec<_>>()
        .join(", ");
    let mut insert = target
        .prepare(&format!(
            "INSERT INTO {} VALUES ({placeholders})",
            quote_identifier(table)
        ))
        .map_err(|error| error.to_string())?;
    let mut rows = source_statement
        .query([])
        .map_err(|error| error.to_string())?;
    let mut sanitized_values = 0;
    while let Some(row) = rows.next().map_err(|error| error.to_string())? {
        let mut values = Vec::with_capacity(columns.len());
        for (index, column) in columns.iter().enumerate() {
            let value = row.get_ref(index).map_err(|error| error.to_string())?;
            let sanitize = sensitive.contains(&column.name)
                && matches!(value, ValueRef::Text(_) | ValueRef::Blob(_));
            if sanitize {
                sanitized_values += 1;
            }
            values.push(owned_sanitized_value(value, sanitize));
        }
        insert
            .execute(params_from_iter(values))
            .map_err(|error| format!("could not copy sanitized row from {table}: {error}"))?;
    }
    Ok((sensitive, sanitized_values))
}

struct LegacyColumn {
    name: String,
    affinity: &'static str,
}

fn table_columns(connection: &Connection, table: &str) -> Result<Vec<LegacyColumn>, String> {
    let mut statement = connection
        .prepare(&format!("PRAGMA table_info({})", quote_identifier(table)))
        .map_err(|error| error.to_string())?;
    let rows = statement
        .query_map([], |row| {
            let name = row.get::<_, String>(1)?;
            let declared = row.get::<_, String>(2)?;
            Ok(LegacyColumn {
                name,
                affinity: portable_sqlite_affinity(&declared),
            })
        })
        .map_err(|error| error.to_string())?;
    rows.collect::<Result<Vec<_>, _>>()
        .map_err(|error| error.to_string())
}

fn portable_sqlite_affinity(declared: &str) -> &'static str {
    let declared = declared.to_ascii_uppercase();
    if declared.contains("INT") {
        "INTEGER"
    } else if declared.contains("CHAR") || declared.contains("CLOB") || declared.contains("TEXT") {
        "TEXT"
    } else if declared.contains("REAL") || declared.contains("FLOA") || declared.contains("DOUB") {
        "REAL"
    } else if declared.is_empty() || declared.contains("BLOB") {
        "BLOB"
    } else {
        "NUMERIC"
    }
}

fn legacy_query_column_is_safe(column: &str) -> bool {
    let column = column.to_ascii_lowercase();
    column == "id"
        || column.ends_with("_id")
        || matches!(
            column.as_str(),
            "source"
                | "category"
                | "method"
                | "kind"
                | "status"
                | "mode"
                | "backend"
                | "protocol"
                | "target_type"
                | "access"
                | "tier"
                | "metric"
                | "rule"
                | "anchor_kind"
                | "hash"
                | "sha256"
        )
}

fn owned_sanitized_value(value: ValueRef<'_>, sanitize: bool) -> SqlValue {
    if sanitize {
        return SqlValue::Text("[redacted]".to_string());
    }
    match value {
        ValueRef::Null => SqlValue::Null,
        ValueRef::Integer(value) => SqlValue::Integer(value),
        ValueRef::Real(value) => SqlValue::Real(value),
        ValueRef::Text(value) => SqlValue::Text(String::from_utf8_lossy(value).into_owned()),
        ValueRef::Blob(value) => SqlValue::Blob(value.to_vec()),
    }
}

fn database_digest(connection: &Connection, tables: &[String]) -> Result<(u64, String), String> {
    let mut rows = 0;
    let mut table_digests = Vec::new();
    for table in tables {
        let (table_rows, table_digest) = table_digest(connection, table)?;
        rows += table_rows;
        table_digests.push((table, table_rows, table_digest));
    }
    Ok((
        rows,
        database_digest_from_tables(
            table_digests
                .iter()
                .map(|(table, rows, digest)| (*table, *rows, digest)),
        ),
    ))
}

fn database_digest_from_tables<'a>(
    tables: impl IntoIterator<Item = (&'a String, u64, &'a String)>,
) -> String {
    let mut digest = Sha256::new();
    for (table, rows, table_digest) in tables {
        digest.update(table.as_bytes());
        digest.update(rows.to_le_bytes());
        digest.update(table_digest.as_bytes());
    }
    format!("sha256:{:x}", digest.finalize())
}

fn table_digest(connection: &Connection, table: &str) -> Result<(u64, String), String> {
    table_digest_with_sanitization(connection, table, &BTreeSet::new())
}

fn table_digest_with_sanitization(
    connection: &Connection,
    table: &str,
    sensitive: &BTreeSet<String>,
) -> Result<(u64, String), String> {
    let mut statement = connection
        .prepare(&format!("SELECT * FROM {}", quote_identifier(table)))
        .map_err(|error| error.to_string())?;
    let columns = statement
        .column_names()
        .into_iter()
        .map(str::to_string)
        .collect::<Vec<_>>();
    let mut query = statement.query([]).map_err(|error| error.to_string())?;
    let mut row_digests = Vec::new();
    while let Some(row) = query.next().map_err(|error| error.to_string())? {
        let mut digest = Sha256::new();
        for (index, column) in columns.iter().enumerate() {
            digest.update(column.as_bytes());
            let value = row.get_ref(index).map_err(|error| error.to_string())?;
            digest_value_ref(
                &mut digest,
                if sensitive.contains(column)
                    && matches!(value, ValueRef::Text(_) | ValueRef::Blob(_))
                {
                    ValueRef::Text(b"[redacted]")
                } else {
                    value
                },
            );
        }
        row_digests.push(digest.finalize().to_vec());
    }
    row_digests.sort();
    let mut digest = Sha256::new();
    for row in &row_digests {
        digest.update(row);
    }
    Ok((
        row_digests.len() as u64,
        format!("sha256:{:x}", digest.finalize()),
    ))
}

fn digest_value_ref(digest: &mut Sha256, value: ValueRef<'_>) {
    match value {
        ValueRef::Null => digest.update([0]),
        ValueRef::Integer(value) => {
            digest.update([1]);
            digest.update(value.to_le_bytes());
        }
        ValueRef::Real(value) => {
            digest.update([2]);
            digest.update(value.to_bits().to_le_bytes());
        }
        ValueRef::Text(value) => {
            digest.update([3]);
            digest.update((value.len() as u64).to_le_bytes());
            digest.update(value);
        }
        ValueRef::Blob(value) => {
            digest.update([4]);
            digest.update((value.len() as u64).to_le_bytes());
            digest.update(value);
        }
    }
}

fn value_ref_json(value: ValueRef<'_>) -> Value {
    match value {
        ValueRef::Null => Value::Null,
        ValueRef::Integer(value) => Value::Number(value.into()),
        ValueRef::Real(value) => serde_json::Number::from_f64(value)
            .map(Value::Number)
            .unwrap_or(Value::Null),
        ValueRef::Text(value) => Value::String(String::from_utf8_lossy(value).into_owned()),
        ValueRef::Blob(value) => serde_json::json!({
            "base64":base64::engine::general_purpose::STANDARD.encode(value)
        }),
    }
}

fn quote_identifier(identifier: &str) -> String {
    format!("\"{}\"", identifier.replace('"', "\"\""))
}

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

    #[test]
    fn migrates_every_table_with_matching_counts_and_digests_and_queries_joins() {
        let fixture = tempfile::tempdir().unwrap();
        let source = fixture.path().join("legacy-source.sqlite");
        let index = fixture.path().join("sanitized.sqlite");
        let connection = Connection::open(&source).unwrap();
        connection
            .execute_batch(
                "CREATE TABLE events(id INTEGER PRIMARY KEY, ts INTEGER, session_id TEXT, data TEXT);
                 CREATE TABLE captures(id TEXT PRIMARY KEY, ts INTEGER, session_id TEXT, screenshot_path TEXT);
                 INSERT INTO events VALUES(1, 10, 's0', '{\"kind\":\"console\"}');
                 INSERT INTO events VALUES(2, 20, 's0', '{\"kind\":\"route\"}');
                 INSERT INTO captures VALUES('c0', 15, 's0', '/tmp/capture.png');",
            )
            .unwrap();
        drop(connection);

        let migrated = migrate_legacy_debugger(&source, Some(&index), false).unwrap();
        assert!(migrated.matched);
        assert_eq!(migrated.tables.len(), 2);
        assert_eq!(migrated.total_rows, 3);
        assert_ne!(migrated.source_digest, migrated.target_digest);
        assert_eq!(migrated.sanitized_source_digest, migrated.target_digest);
        assert_eq!(migrated.sanitized_values, 3);

        let result = query_legacy_debugger(
            Some(&index),
            "SELECT events.id, captures.screenshot_path FROM events JOIN captures USING(session_id) ORDER BY events.id",
            10,
        )
        .unwrap();
        assert_eq!(result.rows.len(), 2);
        assert_eq!(result.rows[0]["id"], 1);
        assert_eq!(result.rows[0]["screenshot_path"], "[redacted]");
        assert!(!result.truncated);
    }

    #[test]
    fn query_rejects_mutation_and_caps_rows() {
        let fixture = tempfile::tempdir().unwrap();
        let index = fixture.path().join("index.sqlite");
        let connection = Connection::open(&index).unwrap();
        connection
            .execute_batch("CREATE TABLE events(id INTEGER); INSERT INTO events VALUES(1),(2),(3);")
            .unwrap();
        drop(connection);
        assert!(query_legacy_debugger(Some(&index), "DELETE FROM events", 10).is_err());
        assert!(
            query_legacy_debugger(
                Some(&index),
                "WITH removed AS (DELETE FROM events RETURNING id) SELECT * FROM removed",
                10
            )
            .is_err()
        );
        let result =
            query_legacy_debugger(Some(&index), "SELECT * FROM events ORDER BY id", 2).unwrap();
        assert_eq!(result.rows.len(), 2);
        assert!(result.truncated);
    }

    #[cfg(unix)]
    #[test]
    fn artifact_preflight_rejects_symlinks_without_following_them() {
        use std::os::unix::fs::symlink;

        let fixture = tempfile::tempdir().unwrap();
        let target = fixture.path().join("target.json");
        let link = fixture.path().join("trace.json");
        std::fs::write(&target, b"secret legacy trace").unwrap();
        symlink(&target, &link).unwrap();

        let error = validate_legacy_debugger_artifacts(&[link]).unwrap_err();
        assert!(error.contains("symlinks are not followed"), "{error}");
    }
}