symforge 11.8.1

SymForge — in-memory code intelligence MCP server for Claude Code, Codex, and Gemini CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
//! `secret_remediate` — agent-driven secret remediation (feature 034).
//!
//! Preview defaults to true. Apply is a write tool (harness permission gate).
//! Never returns secret bytes or private keys.

use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Instant;

use rmcp::handler::server::wrapper::Parameters;
use rmcp::{tool, tool_router};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::edit_safety::batch_commit::{
    BatchIo, EmbeddedBatchIo, StagedImage, commit_staged_locked, with_staged_locks,
};
use crate::edit_safety::secret_remediation as shared_stage;
use crate::knowledge;
use crate::knowledge::secret_remediation::{self, SelectionRefusal};
use crate::protocol::SymForgeServer;
use crate::protocol::edit_tools::fail_and_return_mutation_replay;
use crate::protocol::result_status::{OutcomeClass, ResultStatus};
use crate::protocol::secret_dismissals::DISMISSAL_STORE_REL;
use crate::protocol::withheld::RemediationActionName;

const MAX_REMEDIATION_FILE_BYTES: usize = 2 * 1024 * 1024;
const MAX_REMEDIATION_TOTAL_BYTES: usize = 64 * 1024 * 1024;
const MAX_REMEDIATION_SCAN_FILES: usize = 4096;

#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct SecretRemediateInput {
    /// One path, list of paths, or the string `"repo"`.
    pub scope: Value,
    /// Required non-empty finding ids from `_meta["symforge/withheld"]`.
    pub finding_ids: Vec<String>,
    /// `externalize` | `encrypt` | `dismiss`
    pub action: String,
    /// Default true. `false` selects apply (write).
    #[serde(default = "default_preview_true")]
    pub preview: bool,
    /// Honored on apply like the edit lane (durable project-state replay).
    pub idempotency_key: Option<String>,
}

fn default_preview_true() -> bool {
    true
}

#[tool_router(router = secret_remediate_tool_router, vis = "pub(crate)")]
impl SymForgeServer {
    #[tool(
        name = "secret_remediate",
        description = "Preview or apply secret remediation (externalize/encrypt/dismiss). Preview defaults true; apply requires write permission. Never returns secret bytes.",
        annotations(
            read_only_hint = false,
            destructive_hint = true,
            idempotent_hint = true,
            open_world_hint = false
        )
    )]
    pub(crate) async fn secret_remediate_tool(
        &self,
        params: Parameters<SecretRemediateInput>,
    ) -> Result<rmcp::model::CallToolResult, rmcp::ErrorData> {
        let started = Instant::now();
        let input = params.0;
        let preview = input.preview;
        let result = self.secret_remediate_inner(input).await;
        let text = match &result {
            Ok(t) | Err(t) => t.clone(),
        };
        let outcome = if result.is_ok() {
            if text.contains("apply_status: incomplete") {
                OutcomeClass::Ambiguous
            } else {
                OutcomeClass::Found
            }
        } else if text.starts_with("Error:") {
            OutcomeClass::InvalidRequest
        } else {
            OutcomeClass::InternalFailure
        };
        self.record_tool_completion("secret_remediate", &text, started.elapsed(), outcome);
        if preview {
            Ok(ResultStatus::new(outcome).into_call_tool_result(text))
        } else {
            Ok(ResultStatus::new(outcome).into_mutation_call_tool_result(text))
        }
    }
}

impl SymForgeServer {
    async fn secret_remediate_inner(&self, input: SecretRemediateInput) -> Result<String, String> {
        if input.finding_ids.is_empty() {
            return Err(
                "Error: finding_ids must be a non-empty array (empty means reject; no implicit all-in-scope)"
                    .to_string(),
            );
        }
        let action = match input.action.as_str() {
            "externalize" => RemediationActionName::Externalize,
            "encrypt" => RemediationActionName::Encrypt,
            "dismiss" => RemediationActionName::Dismiss,
            other => {
                return Err(format!(
                    "Error: action must be externalize|encrypt|dismiss, got {other:?}"
                ));
            }
        };

        // Idempotency: preview never reserves; apply honors edit-lane replay.
        let idempotency = match begin_secret_replay(self, &input) {
            Ok(active) => active,
            Err(output) => {
                if output.starts_with("Error:") {
                    return Err(output);
                }
                return Ok(output);
            }
        };

        let paths = match resolve_scope_paths(self, &input.scope) {
            Ok(p) => p,
            Err(e) => return Err(fail_and_return_mutation_replay(&idempotency, e)),
        };

        match action {
            RemediationActionName::Externalize => {
                self.run_externalize(&input, &paths, &idempotency).await
            }
            RemediationActionName::Encrypt => self.run_encrypt(&input, &paths, &idempotency).await,
            RemediationActionName::Dismiss => self.run_dismiss(&input, &paths, &idempotency).await,
        }
    }

    async fn run_externalize(
        &self,
        input: &SecretRemediateInput,
        paths: &[String],
        idempotency: &Option<crate::idempotency::ActiveReplay>,
    ) -> Result<String, String> {
        let (root, generation, state_dir) = planning_binding(self)?;
        let selected = select_bounded(&root, paths, &input.finding_ids, "externalize")
            .map_err(|error| fail_and_return_mutation_replay(idempotency, error))?;

        if input.preview {
            let plans = secret_remediation::plan_externalize(selected);
            let mut out = String::from("secret_remediate preview (externalize)\n");
            out.push_str("Files that would be created or modified:\n");
            for plan in &plans {
                out.push_str(&format!("- {}\n", plan.path));
            }
            out.push_str("- .env\n");
            out.push_str("- .gitignore (ensure .env entry)\n");
            out.push_str("\nMasked diff:\n");
            for plan in plans {
                out.push_str(&plan.masked_diff);
                out.push('\n');
            }
            return Ok(out);
        }

        let selected_paths = selected
            .iter()
            .map(|file| file.path.clone())
            .collect::<Vec<_>>();
        let staged = shared_stage::stage_externalize(&root, selected, |path| {
            crate::index_lifecycle::physical_root::read_regular_beneath_root(
                &root,
                Path::new(path),
                MAX_REMEDIATION_FILE_BYTES,
            )
            .map_err(|_| shared_stage::StageError::SourceUnavailable)
        })
        .map_err(|_| {
            fail_and_return_mutation_replay(
                idempotency,
                "Error: externalize staging refused".into(),
            )
        })?;
        let source = guarded_commit(
            self,
            &root,
            generation,
            state_dir.as_deref(),
            &staged,
            idempotency,
        )?;
        let mut rescan = String::from("clean");
        let mut details = String::new();
        for path in &selected_paths {
            let finding = match source
                .read_regular_beneath_anchor(Path::new(path), MAX_REMEDIATION_FILE_BYTES)
            {
                Ok(Some(bytes)) => match knowledge::scan_secret_bytes(path, &bytes) {
                    knowledge::SecretScan::Clean => "clean".to_string(),
                    knowledge::SecretScan::Sensitive { finding_count, .. } => {
                        format!("still_sensitive finding_count={finding_count}")
                    }
                    knowledge::SecretScan::Indeterminate { reason } => {
                        format!("indeterminate {reason:?}")
                    }
                },
                _ => "indeterminate source_unavailable".to_string(),
            };
            if finding != "clean" {
                rescan = finding.clone();
            }
            details.push_str(&format!("rescan ({path}) : {finding}\n"));
        }
        let mut out = format!(
            "secret_remediate apply (externalize)\n{}\nwritten:\n",
            apply_status_for_rescan(&rescan)
        );
        for image in &staged {
            out.push_str(&format!("- {}\n", image.relative.display()));
        }
        out.push_str(&details);
        out.push_str(&history_note(&root));
        out.push('\n');
        complete_guarded_replay(idempotency, &source, &staged, &mut out)?;
        let _ = crate::watcher::reconcile_stale_files(&root, self.index.data_plane());
        Ok(out)
    }

    async fn run_encrypt(
        &self,
        input: &SecretRemediateInput,
        paths: &[String],
        idempotency: &Option<crate::idempotency::ActiveReplay>,
    ) -> Result<String, String> {
        let availability = encrypt_runtime_availability(self);
        if !availability.0 {
            return Err(fail_and_return_mutation_replay(
                idempotency,
                format!("Error: encrypt is unavailable ({})", availability.1),
            ));
        }
        let binary = sops_binary_on_path().ok_or_else(|| {
            fail_and_return_mutation_replay(
                idempotency,
                "Error: encrypt is unavailable (sops_not_installed)".to_string(),
            )
        })?;
        let (root, generation, state_dir) = planning_binding(self)?;
        let selected = select_bounded(&root, paths, &input.finding_ids, "encrypt")
            .map_err(|error| fail_and_return_mutation_replay(idempotency, error))?;
        secret_remediation::ensure_encrypt_formats(&selected).map_err(|error| {
            fail_and_return_mutation_replay(idempotency, selection_error_text(error, "encrypt"))
        })?;
        if input.preview {
            let mut out = String::from(
                "secret_remediate preview (encrypt)\nFiles that would be created or modified:\n",
            );
            for file in &selected {
                out.push_str(&format!("- {}\n", file.path));
            }
            out.push_str("\nMasked summary:\n");
            for file in &selected {
                out.push_str(&format!(
                    "- {}: SOPS encryption with age recipient (public only)\n",
                    file.path
                ));
            }
            return Ok(out);
        }

        let selected_paths = selected
            .iter()
            .map(|file| file.path.clone())
            .collect::<Vec<_>>();
        let deadline = Instant::now() + std::time::Duration::from_secs(300);
        let mut staged = Vec::with_capacity(selected.len());
        for file in selected {
            let timeout = deadline.saturating_duration_since(Instant::now());
            if timeout.is_zero() {
                return Err(fail_and_return_mutation_replay(
                    idempotency,
                    "Error: encrypt preparation deadline exceeded".to_string(),
                ));
            }
            let encrypted = shared_stage::encrypt_selected_bytes(
                &file.path,
                &file.original,
                &binary,
                &availability.1,
                timeout,
                || None,
            )
            .map_err(|reason| {
                fail_and_return_mutation_replay(
                    idempotency,
                    format!("Error: encrypt preparation refused ({reason:?})"),
                )
            })?;
            if secret_remediation::contains_selected_plaintext(&encrypted, &file) {
                return Err(fail_and_return_mutation_replay(
                    idempotency,
                    "Error: encrypt output retained selected plaintext".to_string(),
                ));
            }
            staged.push(StagedImage {
                absolute: root.join(&file.path),
                relative: PathBuf::from(&file.path),
                original: Some(file.original),
                replacement: encrypted,
                owner_only: false,
            });
        }
        let source = guarded_commit(
            self,
            &root,
            generation,
            state_dir.as_deref(),
            &staged,
            idempotency,
        )?;
        let mut rescan = String::from("clean");
        let mut details = String::new();
        for path in &selected_paths {
            let finding = match source
                .read_regular_beneath_anchor(Path::new(path), MAX_REMEDIATION_FILE_BYTES)
            {
                Ok(Some(bytes)) => match knowledge::scan_secret_bytes(path, &bytes) {
                    knowledge::SecretScan::Clean => "clean".to_string(),
                    knowledge::SecretScan::Sensitive { finding_count, .. } => {
                        format!("still_sensitive finding_count={finding_count}")
                    }
                    knowledge::SecretScan::Indeterminate { reason } => {
                        format!("indeterminate {reason:?}")
                    }
                },
                _ => "indeterminate source_unavailable".to_string(),
            };
            if finding != "clean" {
                rescan = finding.clone();
            }
            details.push_str(&format!("rescan ({path}) : {finding}\n"));
        }
        let mut out = format!(
            "secret_remediate apply (encrypt)\n{}\nwritten:\n",
            apply_status_for_rescan(&rescan)
        );
        for image in &staged {
            out.push_str(&format!("- {}\n", image.relative.display()));
        }
        out.push_str(&details);
        out.push_str("plaintext_absent: true\n");
        out.push_str(&history_note(&root));
        out.push('\n');
        complete_guarded_replay(idempotency, &source, &staged, &mut out)?;
        let _ = crate::watcher::reconcile_stale_files(&root, self.index.data_plane());
        Ok(out)
    }

    async fn run_dismiss(
        &self,
        input: &SecretRemediateInput,
        paths: &[String],
        idempotency: &Option<crate::idempotency::ActiveReplay>,
    ) -> Result<String, String> {
        let (root, generation, state_dir) = planning_binding(self)?;
        let selected = select_bounded(&root, paths, &input.finding_ids, "dismiss")
            .map_err(|error| fail_and_return_mutation_replay(idempotency, error))?;
        let records = secret_remediation::plan_dismiss(&selected).map_err(|error| {
            fail_and_return_mutation_replay(idempotency, selection_error_text(error, "dismiss"))
        })?;
        if input.preview {
            let mut out = String::from(
                "secret_remediate preview (dismiss)\nFiles that would be created or modified:\n",
            );
            out.push_str(&format!("- {DISMISSAL_STORE_REL}\n\nMasked summary:\n"));
            for record in &records {
                out.push_str(&format!(
                    "- {} rule={} digest={}\n",
                    record.path,
                    record.rule_id,
                    &record.line_digest[..12.min(record.line_digest.len())],
                ));
            }
            return Ok(out);
        }
        let selected_paths = selected
            .iter()
            .map(|file| file.path.clone())
            .collect::<Vec<_>>();
        let staged = shared_stage::stage_dismiss(&root, &selected, |path| {
            crate::index_lifecycle::physical_root::read_regular_beneath_root(
                &root,
                Path::new(path),
                MAX_REMEDIATION_FILE_BYTES,
            )
            .map_err(|_| shared_stage::StageError::SourceUnavailable)
        })
        .map_err(|error| {
            let reason = match error {
                shared_stage::StageError::SourceUnavailable => {
                    "Error: dismiss apply refused; dismissal store could not be loaded".to_string()
                }
                _ => format!("Error: dismiss staging refused ({error:?})"),
            };
            fail_and_return_mutation_replay(idempotency, reason)
        })?;
        let source = guarded_commit(
            self,
            &root,
            generation,
            state_dir.as_deref(),
            &staged,
            idempotency,
        )?;
        let actual_store = source
            .read_regular_beneath_anchor(Path::new(DISMISSAL_STORE_REL), MAX_REMEDIATION_FILE_BYTES)
            .ok()
            .flatten();
        let current_records = actual_store.as_deref().and_then(|bytes| {
            crate::knowledge::secret_dismissals::parse_dismissals_bytes(bytes).ok()
        });
        use crate::live_index::single_file::{
            ReindexOutcome, admit_and_index_single_path, reconcile_secret_dismissals,
        };
        let shared = self.index.data_plane();
        let mut outcomes = reconcile_secret_dismissals(shared, &root);
        let mut rescan = String::from("clean");
        let mut details = String::new();
        for path in &selected_paths {
            let absolute = root.join(path);
            let readmit = || {
                admit_and_index_single_path(
                    path,
                    &absolute,
                    shared,
                    shared.current_project_generation(),
                )
            };
            let mut outcome = outcomes.remove(path).unwrap_or_else(readmit);
            if matches!(outcome, ReindexOutcome::PublicationRejected) {
                outcome = readmit();
            }
            let index_outcome = match outcome {
                ReindexOutcome::Reindexed | ReindexOutcome::HashSkip => "indexed",
                ReindexOutcome::Skipped => "withheld",
                ReindexOutcome::NotFound | ReindexOutcome::Removed => "absent",
                ReindexOutcome::ReadError(_) => "unreadable",
                ReindexOutcome::PublicationRejected => {
                    "publication rejected by a concurrent index change; index unchanged"
                }
            };
            let finding = match (
                &current_records,
                source.read_regular_beneath_anchor(Path::new(path), MAX_REMEDIATION_FILE_BYTES),
            ) {
                (Some(records), Ok(Some(bytes))) => {
                    match crate::knowledge::secret_dismissals::scan_with_records(
                        path, &bytes, records,
                    ) {
                        knowledge::SecretScan::Clean => "clean".to_string(),
                        knowledge::SecretScan::Sensitive { finding_count, .. } => {
                            format!("still_sensitive finding_count={finding_count}")
                        }
                        knowledge::SecretScan::Indeterminate { reason } => {
                            format!("indeterminate {reason:?}")
                        }
                    }
                }
                _ => "indeterminate source_unavailable".to_string(),
            };
            if finding != "clean" {
                rescan = finding.clone();
            }
            details.push_str(&format!(
                "rescan ({path}) : {finding}\nindex ({path}) : {index_outcome}\n"
            ));
        }
        let mut out = format!(
            "secret_remediate apply (dismiss)\n{}\nwritten:\n- {DISMISSAL_STORE_REL}\n",
            apply_status_for_rescan(&rescan)
        );
        out.push_str(&details);
        out.push_str(&history_note(&root));
        out.push('\n');
        complete_guarded_replay(idempotency, &source, &staged, &mut out)?;
        Ok(out)
    }
}

fn admitted_root_matches(
    root: &Path,
    source: &crate::index_lifecycle::activation::ProjectSourceAuthority,
) -> bool {
    root.canonicalize()
        .is_ok_and(|canonical| canonical == source.admitted_root())
}

/// The replay gate every lane (secret remediation, edit begin, edit probe)
/// runs before it touches a replay store: the bound root must still be the
/// root the source authority admitted, then the state placement is
/// reconciled. One function, so the three lanes cannot drift apart.
pub(crate) fn admitted_replay_state(
    server: &SymForgeServer,
    root: &Path,
    runtime: Option<&crate::domain::ProjectStateDir>,
    source: &crate::index_lifecycle::activation::ProjectSourceAuthority,
    label: &str,
) -> Result<Option<crate::domain::ProjectStateDir>, String> {
    if !admitted_root_matches(root, source) {
        return Err(format!("Error: admitted {label} source changed"));
    }
    resolved_project_state(server, root, runtime, label)
}

/// Reconcile the server's resolved state placement with the pinned index
/// binding for a replay. The roots must canonicalize equal, and two present
/// state dirs must agree. When only one side carries a state dir, that one is
/// the durable placement for this root. `label` names the caller in refusals.
pub(crate) fn resolved_project_state(
    server: &SymForgeServer,
    root: &Path,
    runtime: Option<&crate::domain::ProjectStateDir>,
    label: &str,
) -> Result<Option<crate::domain::ProjectStateDir>, String> {
    let unavailable = || format!("Error: admitted {label} source unavailable");
    let server_root = server.capture_repo_root().ok_or_else(unavailable)?;
    let (Ok(server_canonical), Ok(runtime_canonical)) =
        (server_root.canonicalize(), root.canonicalize())
    else {
        return Err(unavailable());
    };
    if server_canonical != runtime_canonical {
        return Err(format!("Error: admitted {label} source changed"));
    }
    let server_state = server.capture_project_state_dir();
    if let (Some(runtime), Some(server_state)) = (runtime, server_state.as_ref())
        && runtime.as_path() != server_state.as_path()
    {
        return Err("Error: durable project-state placement changed".to_string());
    }
    Ok(server_state.or_else(|| runtime.cloned()))
}

fn begin_secret_replay(
    server: &SymForgeServer,
    input: &SecretRemediateInput,
) -> Result<Option<crate::idempotency::ActiveReplay>, String> {
    // The key is optional (spec 034 contract): without one, apply runs
    // unreplayed, exactly as the edit lane does. An empty key still reaches
    // the idempotency module, which refuses it with its own typed error.
    let Some(raw_key) = input.idempotency_key.as_deref().filter(|_| !input.preview) else {
        return Ok(None);
    };
    let mut request = serde_json::to_value(input)
        .map_err(|_| "Error: remediation request cannot be serialized".to_string())?;
    if let Value::Object(map) = &mut request {
        map.remove("idempotency_key");
    }
    let decision = server
        .index
        .with_admitted_replay_source(|root, state, source| {
            let placement = admitted_replay_state(server, root, state, source, "remediation")?;
            let state = placement.as_ref().ok_or_else(|| {
                "Error: durable project-state replay is unavailable for this binding".to_string()
            })?;
            crate::idempotency::begin_tool_replay_verified_bound(
                state,
                "secret_remediate",
                raw_key,
                &request,
                source,
            )
            .map_err(|error| crate::idempotency::format_tool_error(&error))
        })
        .map_err(|_| "Error: admitted remediation source unavailable".to_string())?
        .ok_or_else(|| "Error: admitted remediation source unavailable".to_string())??;
    match decision {
        crate::idempotency::ReplayStart::FirstExecution(active) => Ok(Some(active)),
        crate::idempotency::ReplayStart::Replay(response) => Err(response),
    }
}

fn planning_binding(server: &SymForgeServer) -> Result<(PathBuf, u64, Option<PathBuf>), String> {
    let shared = server.index.data_plane();
    let live = shared.read();
    let root = live
        .indexed_root
        .clone()
        .ok_or_else(|| "Error: no indexed root bound".to_string())?;
    let generation = shared.current_project_generation();
    let state_dir = resolved_project_state(
        server,
        &root,
        shared.project_state_dir().as_deref(),
        "remediation",
    )?
    .map(|state| state.as_path().to_path_buf());
    Ok((root, generation, state_dir))
}

fn select_bounded(
    root: &Path,
    paths: &[String],
    finding_ids: &[String],
    action: &str,
) -> Result<Vec<secret_remediation::SelectedFile>, String> {
    if paths.len() > MAX_REMEDIATION_SCAN_FILES {
        return Err(selection_error_text(
            SelectionRefusal::ResourceLimit,
            action,
        ));
    }
    let mut total = 0usize;
    secret_remediation::select_requested_checked(paths, finding_ids, |path| {
        let bytes = crate::index_lifecycle::physical_root::read_regular_beneath_root(
            root,
            Path::new(path),
            MAX_REMEDIATION_FILE_BYTES,
        )
        .map_err(|_| SelectionRefusal::ResourceLimit)?;
        if let Some(bytes) = &bytes {
            total = total.saturating_add(bytes.len());
            if total > MAX_REMEDIATION_TOTAL_BYTES {
                return Err(SelectionRefusal::ResourceLimit);
            }
        }
        Ok(bytes)
    })
    .map_err(|error| selection_error_text(error, action))
}

fn guarded_commit(
    server: &SymForgeServer,
    planned_root: &Path,
    planned_generation: u64,
    planned_state: Option<&Path>,
    staged: &[StagedImage],
    idempotency: &Option<crate::idempotency::ActiveReplay>,
) -> Result<Arc<crate::index_lifecycle::activation::ProjectSourceAuthority>, String> {
    with_staged_locks(staged, |order| {
        server.index.with_admitted_write_binding(
            |root, state, generation, authority, publication| {
                if root != planned_root
                    || !admitted_root_matches(planned_root, authority)
                    || generation != planned_generation
                    || state
                        .is_some_and(|state| Some(state.as_path()) != planned_state)
                    || staged.iter().any(|image| image.absolute != root.join(&image.relative))
                {
                    return Err("Error: source binding changed before remediation apply".to_string());
                }
                let write = authority.acquire_write_expected(publication).map_err(|_| {
                    "Error: source publication changed before remediation apply".to_string()
                })?;
                let mut io = EmbeddedBatchIo::new(write);
                for image in staged {
                    match io.matches(image, image.original.as_deref()) {
                        Ok(true) => {}
                        Ok(false) => {
                            let _ = io.finish();
                            return Err("Error: remediation source bytes changed before apply".to_string());
                        }
                        Err(_) => {
                            let _ = io.finish();
                            return Err("Error: remediation source preimage unavailable".to_string());
                        }
                    }
                }
                if let Some(active) = idempotency
                    && active.mark_started().is_err() {
                        let _ = io.finish();
                        return Err("Error: durable remediation start record unavailable".to_string());
                    }
                let committed = commit_staged_locked(staged, order, &mut io, None);
                let finished = io.finish();
                if committed.is_err() || finished.is_err() {
                    if let Some(active) = idempotency {
                        let _ = active.mark_uncertain();
                    }
                    return Err("secret_remediate apply\napply_status: incomplete\nreason: guarded_write_uncertain\n".to_string());
                }
                Ok(Arc::clone(authority))
            },
        )
    })
    .map_err(|_| "Error: remediation target lock unavailable".to_string())?
    .map_err(|_| "Error: admitted source binding unavailable".to_string())?
    .ok_or_else(|| "Error: admitted source is not current".to_string())?
}

fn complete_guarded_replay(
    idempotency: &Option<crate::idempotency::ActiveReplay>,
    source: &crate::index_lifecycle::activation::ProjectSourceAuthority,
    staged: &[StagedImage],
    output: &mut String,
) -> Result<(), String> {
    // Keyless apply has no replay record to complete; the guarded write
    // already committed, so there is nothing left to report as incomplete.
    let Some(active) = idempotency else {
        return Ok(());
    };
    let targets = staged
        .iter()
        .map(|image| crate::idempotency::PostImageTarget {
            path: image.absolute.display().to_string(),
            content_digest: Some(crate::hash::digest_hex(&image.replacement)),
        })
        .collect();
    let receipt = crate::idempotency::PostImageReceipt {
        targets,
        source: None,
        linked_sources: Vec::new(),
    };
    let Some(receipt) = crate::idempotency::bind_post_image_to_source(receipt, source) else {
        let _ = active.mark_uncertain();
        return Err("secret_remediate apply\napply_status: incomplete\nreason: source_post_image_unavailable\n".to_string());
    };
    if active
        .complete_with_post_image(output.clone(), Some(receipt))
        .is_err()
    {
        let _ = active.mark_uncertain();
        output.clear();
        output.push_str("secret_remediate apply\napply_status: incomplete\nreason: replay_completion_unavailable\n");
        return Err(output.clone());
    }
    Ok(())
}

/// Returns (available, reason_or_recipient).
fn encrypt_runtime_availability(server: &SymForgeServer) -> (bool, String) {
    if sops_binary_on_path().is_none() {
        return (false, "sops_not_installed".to_string());
    }
    let live = server.index.data_plane().read();
    let Some(root) = live.indexed_root.as_deref() else {
        return (false, "no_indexed_root".to_string());
    };
    match resolve_age_recipient(root) {
        Ok(r) => (true, r),
        Err(reason) => (false, reason),
    }
}

fn sops_binary_on_path() -> Option<PathBuf> {
    std::env::var_os("PATH").and_then(|paths| {
        std::env::split_paths(&paths).find_map(|dir| {
            let candidate = dir.join(if cfg!(windows) { "sops.exe" } else { "sops" });
            candidate
                .is_file()
                .then(|| std::fs::canonicalize(candidate).ok())
                .flatten()
        })
    })
}

fn resolve_age_recipient(root: &Path) -> Result<String, String> {
    if let Ok(env) = std::env::var("SOPS_AGE_RECIPIENTS") {
        let first = env
            .split(',')
            .map(str::trim)
            .find(|s| !s.is_empty() && s.starts_with("age1"));
        if let Some(r) = first {
            return Ok(r.to_string());
        }
    }
    let sops_yaml = root.join(".sops.yaml");
    if !sops_yaml.is_file() {
        return Err("no_recipient_configured".to_string());
    }
    let text = std::fs::read_to_string(&sops_yaml).map_err(|_| "no_recipient_configured")?;
    for token in text.split_whitespace() {
        let t = token.trim_matches(|c: char| c == '"' || c == '\'' || c == ',');
        if t.starts_with("age1") && t.len() > 16 {
            return Ok(t.to_string());
        }
    }
    Err("no_recipient_configured".to_string())
}

fn resolve_scope_paths(server: &SymForgeServer, scope: &Value) -> Result<Vec<String>, String> {
    let live = server.index.data_plane().read();
    let Some(root) = live.indexed_root.as_deref() else {
        return Err("Error: no indexed root bound".to_string());
    };
    match scope {
        Value::String(s) if s == "repo" => {
            let mut paths: Vec<String> = live
                .all_files()
                .map(|(path, _)| path.replace('\\', "/"))
                .collect();
            paths.sort();
            paths.dedup();
            Ok(paths)
        }
        Value::String(s) => {
            let norm = s.replace('\\', "/");
            crate::discovery::resolve_repo_path(root, &norm)
                .map_err(|e| format!("Error: scope path refused: {e:?}"))?
                .ok_or_else(|| format!("Error: scope path not found: {norm}"))?;
            Ok(vec![norm])
        }
        Value::Array(arr) => {
            let mut out = Vec::new();
            for v in arr {
                let Some(s) = v.as_str() else {
                    return Err("Error: scope array entries must be strings".to_string());
                };
                let norm = s.replace('\\', "/");
                crate::discovery::resolve_repo_path(root, &norm)
                    .map_err(|e| format!("Error: scope path refused: {e:?}"))?
                    .ok_or_else(|| format!("Error: scope path not found: {norm}"))?;
                out.push(norm);
            }
            Ok(out)
        }
        _ => Err("Error: scope must be a path string, path array, or \"repo\"".to_string()),
    }
}

fn selection_error_text(error: SelectionRefusal, action: &str) -> String {
    match error {
        SelectionRefusal::EmptyFindings => "Error: finding_ids must be non-empty".to_owned(),
        SelectionRefusal::DuplicateFinding => "Error: duplicate finding_id".to_owned(),
        SelectionRefusal::TooManyFindings => "Error: too many finding_ids".to_owned(),
        SelectionRefusal::ScanIndeterminate => {
            format!("Error: secret span scan indeterminate; refusing {action}")
        }
        SelectionRefusal::MissingFinding => "Error: finding_ids not found in scope".to_owned(),
        SelectionRefusal::UndismissableFinding => {
            "Error: finding rule cannot be dismissed".to_owned()
        }
        SelectionRefusal::MissingLine => "Error: could not bind line digest".to_owned(),
        SelectionRefusal::UnsupportedEncryptFormat => {
            "Error: finding is not in an encrypt-supported format".to_owned()
        }
        SelectionRefusal::ResourceLimit => "Error: remediation scan resource limit".to_owned(),
        SelectionRefusal::Cancelled => "Error: remediation scan cancelled".to_owned(),
        SelectionRefusal::DeadlineExceeded => {
            "Error: remediation scan deadline exceeded".to_owned()
        }
    }
}

/// Same honesty rule for externalize, encrypt, and dismiss: a rescan that
/// is still sensitive is not `ok`.
fn apply_status_for_rescan(rescan: &str) -> &'static str {
    if rescan.starts_with("still_sensitive") {
        "apply_status: incomplete (rescan still_sensitive)"
    } else {
        "apply_status: ok"
    }
}

fn history_note(root: &Path) -> String {
    match crate::git::head_sha(root) {
        Ok(sha) => format!("history_note: old value may remain in git history since commit {sha}"),
        Err(_) => "history_note: working tree / uncommitted — no commit SHA observed".to_string(),
    }
}

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

    /// A binding whose root is not the root the source authority admitted is
    /// refused by the shared gate before any replay store is opened, and all
    /// three replay lanes route through that gate.
    #[test]
    fn replay_gate_refuses_a_root_the_source_authority_did_not_admit() {
        let bound = tempfile::tempdir().unwrap();
        let other = tempfile::tempdir().unwrap();
        let state = crate::domain::ProjectStateDir::new(bound.path().join("never-created"));
        let server = super::SymForgeServer::new(
            crate::live_index::LiveIndex::load(bound.path()).unwrap(),
            "replay-gate".to_string(),
            std::sync::Arc::new(parking_lot::Mutex::new(
                crate::watcher::WatcherInfo::default(),
            )),
            Some(bound.path().to_path_buf()),
            None,
        );

        let foreign = crate::index_lifecycle::activation::project_source_authority(other.path());
        for label in ["edit", "remediation"] {
            assert_eq!(
                super::admitted_replay_state(&server, bound.path(), Some(&state), &foreign, label),
                Err(format!("Error: admitted {label} source changed"))
            );
        }
        assert!(
            !state.as_path().exists(),
            "a refused gate must not touch the replay state"
        );

        // Positive control: the authority for the bound root itself passes.
        let own = crate::index_lifecycle::activation::project_source_authority(bound.path());
        assert!(super::admitted_replay_state(&server, bound.path(), None, &own, "edit").is_ok());

        let edit_lanes = include_str!("edit_tools.rs");
        let secret_lane = include_str!("secret_remediate.rs");
        assert_eq!(
            edit_lanes
                .matches("secret_remediate::admitted_replay_state(")
                .count(),
            2,
            "edit begin and probe must both run the shared replay gate"
        );
        assert!(
            secret_lane
                .contains("admitted_replay_state(server, root, state, source, \"remediation\")")
        );
    }

    #[test]
    fn still_sensitive_rescan_is_incomplete() {
        assert_eq!(
            apply_status_for_rescan("still_sensitive finding_count=1"),
            "apply_status: incomplete (rescan still_sensitive)"
        );
        assert_eq!(apply_status_for_rescan("clean"), "apply_status: ok");
        assert_eq!(
            apply_status_for_rescan("indeterminate TooLarge"),
            "apply_status: ok"
        );
        assert_eq!(
            apply_status_for_rescan("unreadable after write: boom"),
            "apply_status: ok"
        );
    }
}