perspt-agent 0.6.1

SRBN Orchestrator and Agent logic for Perspt
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
//! Artifact bundle parsing, transactional application, and path filtering.

use super::*;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

impl SRBNOrchestrator {
    /// PSP-7: Typed parse pipeline returning structured state for every LLM response.
    ///
    /// Replaces the Option-based `parse_artifact_bundle` with a pipeline that
    /// classifies every response through Layers A→E and returns a typed result.
    ///
    /// - **Layer A**: Raw capture — fingerprints the response (hash + length).
    /// - **Layer B**: Path normalization via the hardened `normalize_artifact_path`.
    /// - **Layer C**: Strict JSON parse via `extract_and_deserialize`.
    /// - **Layer D**: Tolerant file-marker recovery via `extract_file_markers`.
    /// - **Layer E**: Semantic validation — declared paths, plugin support files, command policy.
    ///
    /// Returns `(Option<ArtifactBundle>, ParseResultState, Option<CorrectionAttemptRecord>)`.
    pub fn parse_artifact_bundle_typed(
        &self,
        content: &str,
        node_id: &str,
        attempt: u32,
    ) -> (
        Option<perspt_core::types::ArtifactBundle>,
        perspt_core::types::ParseResultState,
        Option<perspt_core::types::CorrectionAttemptRecord>,
    ) {
        use perspt_core::types::{
            ArtifactBundle, ArtifactOperation, CorrectionAttemptRecord, ParseResultState,
            RetryClassification,
        };

        // Layer A: raw capture — fingerprint the response
        let response_fingerprint = {
            let mut hasher = DefaultHasher::new();
            content.hash(&mut hasher);
            format!("{:016x}", hasher.finish())
        };
        let response_length = content.len();
        let created_at = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs() as i64;

        let classify_retry = |state: ParseResultState, rejection: Option<&str>| match state {
            ParseResultState::StrictJsonOk | ParseResultState::TolerantRecoveryOk => None,
            ParseResultState::NoStructuredPayload
            | ParseResultState::SchemaInvalid
            | ParseResultState::EmptyBundle => Some(RetryClassification::MalformedRetry),
            ParseResultState::SemanticallyRejected => {
                let reason = rejection.unwrap_or_default().to_ascii_lowercase();
                if reason.contains("all artifacts rejected")
                    || reason.contains("undeclared")
                    || reason.contains("target")
                {
                    Some(RetryClassification::Retarget)
                } else if reason.contains("support") {
                    Some(RetryClassification::SupportFileViolation)
                } else {
                    Some(RetryClassification::Replan)
                }
            }
        };

        let build_record = |state: ParseResultState, accepted: bool, rejection: Option<String>| {
            let retry_classification = classify_retry(state, rejection.as_deref());
            CorrectionAttemptRecord {
                attempt,
                parse_state: state,
                retry_classification,
                response_fingerprint: response_fingerprint.clone(),
                response_length,
                energy_after: None,
                accepted,
                rejection_reason: rejection,
                created_at,
            }
        };

        // Layer C: Strict JSON parse. Keep JSON extraction and schema
        // deserialization separate so malformed bundles are classified as
        // SchemaInvalid rather than collapsing to NoStructuredPayload.
        match perspt_core::normalize::extract_json(content) {
            Ok(output) => {
                let bundle = match serde_json::from_str::<ArtifactBundle>(&output.json_body) {
                    Ok(bundle) => {
                        log::info!(
                            "Parsed ArtifactBundle via normalization ({})",
                            output.method
                        );
                        bundle
                    }
                    Err(e) => {
                        let record = build_record(
                            ParseResultState::SchemaInvalid,
                            false,
                            Some(format!(
                                "JSON extracted via {} but bundle schema deserialization failed: {}",
                                output.method, e
                            )),
                        );
                        return (None, ParseResultState::SchemaInvalid, Some(record));
                    }
                };

                if bundle.validate().is_ok() {
                    // Layer B: normalize all paths in the bundle
                    let bundle = self.normalize_bundle_paths(bundle);

                    if bundle.artifacts.is_empty() {
                        let record = build_record(
                            ParseResultState::EmptyBundle,
                            false,
                            Some("Bundle is empty after path normalization".to_string()),
                        );
                        return (None, ParseResultState::EmptyBundle, Some(record));
                    }

                    // Layer E: semantic validation
                    match self.semantic_validate_bundle(&bundle, node_id) {
                        Ok(filtered) => {
                            if filtered.artifacts.is_empty() {
                                let record = build_record(
                                    ParseResultState::SemanticallyRejected,
                                    false,
                                    Some(
                                        "All artifacts rejected by semantic validation".to_string(),
                                    ),
                                );
                                return (
                                    None,
                                    ParseResultState::SemanticallyRejected,
                                    Some(record),
                                );
                            }
                            let record = build_record(ParseResultState::StrictJsonOk, true, None);
                            return (Some(filtered), ParseResultState::StrictJsonOk, Some(record));
                        }
                        Err(reason) => {
                            let record = build_record(
                                ParseResultState::SemanticallyRejected,
                                false,
                                Some(reason),
                            );
                            return (None, ParseResultState::SemanticallyRejected, Some(record));
                        }
                    }
                } else {
                    log::warn!("JSON bundle found but failed schema validation");
                    let record = build_record(
                        ParseResultState::SchemaInvalid,
                        false,
                        Some("JSON parsed but bundle schema validation failed".to_string()),
                    );
                    return (None, ParseResultState::SchemaInvalid, Some(record));
                }
            }
            Err(e) => {
                log::debug!("Normalization could not extract ArtifactBundle JSON: {}", e);
            }
        }

        // Layer D: Tolerant file-marker recovery
        let markers = perspt_core::normalize::extract_file_markers(content);
        if !markers.is_empty() {
            let artifacts: Vec<ArtifactOperation> = markers
                .into_iter()
                .filter_map(|m| {
                    let path = m.path?;
                    if m.content.is_empty() {
                        return None;
                    }
                    if m.is_diff {
                        Some(ArtifactOperation::Diff {
                            path,
                            patch: m.content,
                        })
                    } else {
                        Some(ArtifactOperation::Write {
                            path,
                            content: m.content,
                        })
                    }
                })
                .collect();

            if artifacts.is_empty() {
                let record = build_record(
                    ParseResultState::NoStructuredPayload,
                    false,
                    Some("File markers found but no named artifacts extracted".to_string()),
                );
                return (None, ParseResultState::NoStructuredPayload, Some(record));
            }

            let bundle = ArtifactBundle {
                artifacts,
                commands: vec![],
            };
            let bundle = self.normalize_bundle_paths(bundle);

            log::info!(
                "Tolerant recovery extracted {}-artifact bundle via file markers",
                bundle.len()
            );

            // Layer E: semantic validation
            match self.semantic_validate_bundle(&bundle, node_id) {
                Ok(filtered) => {
                    if filtered.artifacts.is_empty() {
                        let record = build_record(
                            ParseResultState::SemanticallyRejected,
                            false,
                            Some("All artifacts rejected by semantic validation".to_string()),
                        );
                        return (None, ParseResultState::SemanticallyRejected, Some(record));
                    }
                    let record = build_record(ParseResultState::TolerantRecoveryOk, true, None);
                    return (
                        Some(filtered),
                        ParseResultState::TolerantRecoveryOk,
                        Some(record),
                    );
                }
                Err(reason) => {
                    let record =
                        build_record(ParseResultState::SemanticallyRejected, false, Some(reason));
                    return (None, ParseResultState::SemanticallyRejected, Some(record));
                }
            }
        }

        // No structured payload at all
        let record = build_record(
            ParseResultState::NoStructuredPayload,
            false,
            Some("No JSON bundle or file markers found in response".to_string()),
        );
        (None, ParseResultState::NoStructuredPayload, Some(record))
    }

    /// Normalize all paths in a bundle through the hardened path normalizer.
    fn normalize_bundle_paths(
        &self,
        mut bundle: perspt_core::types::ArtifactBundle,
    ) -> perspt_core::types::ArtifactBundle {
        bundle.artifacts = bundle
            .artifacts
            .into_iter()
            .filter_map(|op| match op {
                perspt_core::types::ArtifactOperation::Write { path, content } => {
                    match perspt_core::path::normalize_artifact_path(&path) {
                        Ok(normalized) => Some(perspt_core::types::ArtifactOperation::Write {
                            path: normalized,
                            content,
                        }),
                        Err(e) => {
                            log::warn!("Dropping write artifact with bad path '{}': {}", path, e);
                            None
                        }
                    }
                }
                perspt_core::types::ArtifactOperation::Diff { path, patch } => {
                    match perspt_core::path::normalize_artifact_path(&path) {
                        Ok(normalized) => Some(perspt_core::types::ArtifactOperation::Diff {
                            path: normalized,
                            patch,
                        }),
                        Err(e) => {
                            log::warn!("Dropping diff artifact with bad path '{}': {}", path, e);
                            None
                        }
                    }
                }
                perspt_core::types::ArtifactOperation::Delete { path } => {
                    match perspt_core::path::normalize_artifact_path(&path) {
                        Ok(normalized) => {
                            Some(perspt_core::types::ArtifactOperation::Delete { path: normalized })
                        }
                        Err(e) => {
                            log::warn!("Dropping delete artifact with bad path '{}': {}", path, e);
                            None
                        }
                    }
                }
                perspt_core::types::ArtifactOperation::Move { from, to } => {
                    let from_norm = perspt_core::path::normalize_artifact_path(&from);
                    let to_norm = perspt_core::path::normalize_artifact_path(&to);
                    match (from_norm, to_norm) {
                        (Ok(f), Ok(t)) => {
                            Some(perspt_core::types::ArtifactOperation::Move { from: f, to: t })
                        }
                        _ => {
                            log::warn!("Dropping move artifact with bad paths '{}'→'{}'", from, to);
                            None
                        }
                    }
                }
            })
            .collect();
        bundle
    }

    /// PSP-7 Layer E: Semantic validation of a parsed bundle.
    ///
    /// Extends `filter_bundle_to_declared_paths` with plugin-driven checks:
    /// - Legal support files (from plugin `legal_support_files()`)
    /// - Dependency command policy (from plugin `dependency_command_policy()`)
    ///
    /// Returns `Ok(filtered_bundle)` or `Err(reason)` if validation fails hard.
    fn semantic_validate_bundle(
        &self,
        bundle: &perspt_core::types::ArtifactBundle,
        node_id: &str,
    ) -> Result<perspt_core::types::ArtifactBundle, String> {
        let allowed_paths = self.allowed_bundle_paths(node_id);

        // If no output targets declared, pass everything through
        if allowed_paths.is_empty() {
            return Ok(bundle.clone());
        }

        // Get legal support files from the plugin
        let registry = perspt_core::plugin::PluginRegistry::new();
        let plugin_name = self
            .node_indices
            .get(node_id)
            .map(|idx| self.graph[*idx].owner_plugin.as_str())
            .unwrap_or("");
        let plugin = registry.get(plugin_name);
        let legal_support: std::collections::HashSet<String> = plugin
            .map(|p| {
                p.legal_support_files()
                    .iter()
                    .map(|s| s.to_string())
                    .collect()
            })
            .unwrap_or_default();

        let (kept, dropped): (Vec<_>, Vec<_>) = bundle.artifacts.iter().cloned().partition(|a| {
            let normalized = perspt_core::path::normalize_artifact_path(a.path())
                .unwrap_or_else(|_| a.path().to_string());

            if let Some(plugin) = plugin {
                if Self::is_manifest_path(&normalized)
                    && plugin.manifest_mutation_policy(&normalized)
                        == perspt_core::types::ManifestMutationPolicy::Deny
                {
                    log::warn!(
                        "Rejecting manifest mutation '{}' by plugin policy for '{}'",
                        normalized,
                        plugin_name
                    );
                    return false;
                }
            }

            // Accept if in declared output targets
            if allowed_paths.contains(&normalized) {
                return true;
            }

            // Accept if it's a legal support file
            let filename = std::path::Path::new(&normalized)
                .file_name()
                .map(|f| f.to_string_lossy().to_string())
                .unwrap_or_default();
            if legal_support.contains(&filename) {
                log::info!(
                    "Accepting support file '{}' via plugin legal_support_files",
                    normalized
                );
                return true;
            }

            false
        });

        if !dropped.is_empty() {
            let dropped_paths: Vec<String> = dropped.iter().map(|a| a.path().to_string()).collect();
            log::warn!(
                "Semantic validation stripped {} artifact(s) from node '{}': {}",
                dropped.len(),
                node_id,
                dropped_paths.join(", ")
            );
        }

        // Validate commands via plugin dependency_command_policy
        let mut validated_commands = Vec::new();
        for cmd in &bundle.commands {
            let decision = self
                .node_indices
                .get(node_id)
                .and_then(|idx| {
                    let plugin_name = &self.graph[*idx].owner_plugin;
                    let registry = perspt_core::plugin::PluginRegistry::new();
                    registry
                        .get(plugin_name)
                        .map(|p| p.dependency_command_policy(cmd))
                })
                .unwrap_or(perspt_core::types::CommandPolicyDecision::Allow);

            match decision {
                perspt_core::types::CommandPolicyDecision::Allow => {
                    validated_commands.push(cmd.clone());
                }
                perspt_core::types::CommandPolicyDecision::RequireApproval => {
                    log::info!("Command '{}' requires approval — including with flag", cmd);
                    validated_commands.push(cmd.clone());
                }
                perspt_core::types::CommandPolicyDecision::Deny => {
                    log::warn!("Command '{}' denied by plugin policy", cmd);
                }
            }
        }

        Ok(perspt_core::types::ArtifactBundle {
            artifacts: kept,
            commands: validated_commands,
        })
    }

    /// PSP-5: Apply an artifact bundle transactionally
    ///
    /// All file operations are validated first, then applied.
    /// PSP-5 Phase 2: Validates ownership boundaries before applying.
    /// If any operation fails, the method returns an error describing which operation
    /// failed, and previous successful operations are logged for manual review.
    pub async fn apply_bundle_transactionally(
        &mut self,
        bundle: &perspt_core::types::ArtifactBundle,
        node_id: &str,
        node_class: perspt_core::types::NodeClass,
    ) -> Result<()> {
        let idx =
            self.node_indices.get(node_id).copied().ok_or_else(|| {
                anyhow::anyhow!("Unknown node '{}' for bundle application", node_id)
            })?;
        let node_workdir = self.effective_working_dir(idx);

        // Validate structural integrity first
        bundle.validate().map_err(|e| {
            eprintln!(
                "[SRBN-DIAG] Bundle validation failed for '{}': {}",
                node_id, e
            );
            anyhow::anyhow!(e)
        })?;

        // Filter out undeclared paths instead of failing the entire session
        let filtered = self
            .semantic_validate_bundle(bundle, node_id)
            .map_err(|reason| {
                anyhow::anyhow!(
                    "Bundle semantic validation failed for '{}': {}",
                    node_id,
                    reason
                )
            })?;

        // If filtering removed ALL artifacts, fail so the correction loop can
        // retry with proper paths.  The old fallback applied the *unfiltered*
        // bundle, causing cross-node file pollution (e.g., overwriting root
        // Cargo.toml with a crate-level manifest).
        if filtered.artifacts.is_empty() && !bundle.artifacts.is_empty() {
            let dropped_paths: Vec<String> = bundle
                .artifacts
                .iter()
                .map(|a| a.path().to_string())
                .collect();
            eprintln!(
                "[SRBN-DIAG] All artifacts stripped for '{}': {:?}",
                node_id, dropped_paths
            );
            log::warn!(
                "All artifacts stripped for node '{}' — skipping bundle application. \
                 Dropped paths: {}",
                node_id,
                dropped_paths.join(", ")
            );
            self.emit_log(format!(
                "⚠️ All artifacts for '{}' targeted undeclared paths — bundle skipped. \
                 The actuator's output_files don't match the plan.",
                node_id
            ));
            return Err(anyhow::anyhow!(
                "All {} artifact(s) targeted undeclared paths for node '{}': [{}]. \
                 Expected paths: {:?}",
                bundle.artifacts.len(),
                node_id,
                dropped_paths.join(", "),
                self.node_indices
                    .get(node_id)
                    .map(|idx| self.graph[*idx]
                        .output_targets
                        .iter()
                        .map(|p| p.to_string_lossy().to_string())
                        .collect::<Vec<_>>())
                    .unwrap_or_default()
            ));
        }
        let bundle = filtered;

        // PSP-5 Phase 2: Validate ownership boundaries (soft failure)
        // Instead of crashing the session, log ownership conflicts and
        // continue — the LLM often generates shared files (e.g. config.json)
        // from multiple nodes.
        if let Err(e) = self
            .context
            .ownership_manifest
            .validate_bundle(&bundle, node_id, node_class)
        {
            log::warn!("Ownership validation warning for node '{}': {}", node_id, e);
            self.emit_log(format!("⚠️ Ownership warning: {}", e));
        }

        // PSP-5 Phase 2: Determine owner_plugin for new path assignment
        let owner_plugin = self
            .node_indices
            .get(node_id)
            .and_then(|idx| {
                let plugin = &self.graph[*idx].owner_plugin;
                if plugin.is_empty() {
                    None
                } else {
                    Some(plugin.clone())
                }
            })
            .unwrap_or_else(|| "unknown".to_string());

        let mut files_created: Vec<String> = Vec::new();
        let mut files_modified: Vec<String> = Vec::new();
        let mut files_deleted: Vec<String> = Vec::new();

        for op in &bundle.artifacts {
            let mut args = HashMap::new();
            let resolved_path = node_workdir.join(op.path());
            args.insert(
                "path".to_string(),
                resolved_path.to_string_lossy().to_string(),
            );

            let call = match op {
                perspt_core::types::ArtifactOperation::Write { content, .. } => {
                    args.insert("content".to_string(), content.clone());
                    ToolCall {
                        name: "write_file".to_string(),
                        arguments: args,
                    }
                }
                perspt_core::types::ArtifactOperation::Diff { patch, .. } => {
                    args.insert("diff".to_string(), patch.clone());
                    ToolCall {
                        name: "apply_diff".to_string(),
                        arguments: args,
                    }
                }
                perspt_core::types::ArtifactOperation::Delete { path } => {
                    // Validate delete through policy layer
                    if let Err(e) = perspt_policy::sanitize::validate_artifact_mutation(
                        path,
                        &self.context.working_dir,
                        "Delete",
                    ) {
                        log::warn!("Delete blocked by policy: {}", e);
                        self.emit_log(format!("⚠️ Delete blocked: {}", e));
                        continue;
                    }
                    ToolCall {
                        name: "delete_file".to_string(),
                        arguments: args,
                    }
                }
                perspt_core::types::ArtifactOperation::Move { from, to } => {
                    // Validate both source and destination through policy
                    if let Err(e) = perspt_policy::sanitize::validate_artifact_mutation(
                        from,
                        &self.context.working_dir,
                        "Move",
                    ) {
                        log::warn!("Move source blocked by policy: {}", e);
                        self.emit_log(format!("⚠️ Move blocked: {}", e));
                        continue;
                    }
                    if let Err(e) = perspt_policy::sanitize::validate_artifact_mutation(
                        to,
                        &self.context.working_dir,
                        "Move",
                    ) {
                        log::warn!("Move destination blocked by policy: {}", e);
                        self.emit_log(format!("⚠️ Move blocked: {}", e));
                        continue;
                    }
                    let resolved_to = node_workdir.join(to);
                    args.insert("from".to_string(), args["path"].clone());
                    args.insert("to".to_string(), resolved_to.to_string_lossy().to_string());
                    ToolCall {
                        name: "move_file".to_string(),
                        arguments: args,
                    }
                }
            };

            let result = self.tools.execute(&call).await;
            if result.success {
                let full_path = resolved_path.clone();

                if op.is_write() {
                    files_created.push(op.path().to_string());
                } else if op.is_delete() {
                    files_deleted.push(op.path().to_string());
                    self.emit_event(perspt_core::AgentEvent::FileDeleted {
                        node_id: self.graph[idx].node_id.clone(),
                        path: op.path().to_string(),
                    });
                } else if op.is_move() {
                    if let perspt_core::types::ArtifactOperation::Move { to, .. } = op {
                        files_modified.push(format!("{} -> {}", op.path(), to));
                        self.emit_event(perspt_core::AgentEvent::FileMoved {
                            node_id: self.graph[idx].node_id.clone(),
                            from: op.path().to_string(),
                            to: to.to_string(),
                        });
                    }
                } else {
                    files_modified.push(op.path().to_string());
                }

                // Track for LSP notification (skip for deleted files)
                if !op.is_delete() {
                    self.last_written_file = Some(full_path.clone());
                    self.file_version += 1;

                    // Notify LSP of file change
                    let registry = perspt_core::plugin::PluginRegistry::new();
                    for (lang, client) in self.lsp_clients.iter_mut() {
                        // Only notify if the plugin owns this file
                        let should_notify = match registry.get(lang) {
                            Some(plugin) => plugin.owns_file(op.path()),
                            None => true,
                        };
                        if should_notify {
                            if let Ok(content) = std::fs::read_to_string(&full_path) {
                                let _ = client
                                    .did_change(&full_path, &content, self.file_version)
                                    .await;
                            }
                        }
                    }
                }

                log::info!("✓ Applied: {}", op.path());
                self.emit_log(format!("✅ Applied: {}", op.path()));
            } else {
                log::warn!("Failed to apply {}: {:?}", op.path(), result.error);
                self.emit_log(format!("❌ Failed: {} - {:?}", op.path(), result.error));
                self.last_tool_failure = result.error.clone();
                return Err(anyhow::anyhow!(
                    "Bundle application failed at {}: {:?}",
                    op.path(),
                    result.error
                ));
            }
        }

        // PSP-5 Phase 2: Auto-assign unregistered paths to this node
        self.context.ownership_manifest.assign_new_paths(
            &bundle,
            node_id,
            &owner_plugin,
            node_class,
        );

        // Emit BundleApplied event
        self.emit_event(perspt_core::AgentEvent::BundleApplied {
            node_id: node_id.to_string(),
            files_created,
            files_modified,
            writes_count: bundle.writes_count(),
            diffs_count: bundle.diffs_count(),
            node_class: node_class.to_string(),
        });

        self.last_tool_failure = None;
        Ok(())
    }

    fn allowed_bundle_paths(&self, node_id: &str) -> std::collections::HashSet<String> {
        self.node_indices
            .get(node_id)
            .map(|idx| {
                self.graph[*idx]
                    .output_targets
                    .iter()
                    .map(|p| {
                        let raw = p.to_string_lossy();
                        perspt_core::path::normalize_artifact_path(&raw)
                            .unwrap_or_else(|_| raw.to_string())
                    })
                    .collect()
            })
            .unwrap_or_default()
    }

    fn is_manifest_path(path: &str) -> bool {
        matches!(
            std::path::Path::new(path)
                .file_name()
                .and_then(|name| name.to_str()),
            Some("Cargo.toml" | "package.json" | "pyproject.toml" | "setup.py" | "setup.cfg")
        )
    }
}

#[cfg(test)]
mod tests {
    use perspt_core::types::{ArtifactBundle, ArtifactOperation, ParseResultState};

    #[test]
    fn test_parse_result_state_is_ok() {
        assert!(ParseResultState::StrictJsonOk.is_ok());
        assert!(ParseResultState::TolerantRecoveryOk.is_ok());
        assert!(!ParseResultState::NoStructuredPayload.is_ok());
        assert!(!ParseResultState::SchemaInvalid.is_ok());
        assert!(!ParseResultState::SemanticallyRejected.is_ok());
        assert!(!ParseResultState::EmptyBundle.is_ok());
    }

    #[test]
    fn test_strict_json_layer_c_valid_bundle() {
        // Layer C: strict JSON parse succeeds for a well-formed bundle
        let json = r#"{"artifacts":[{"operation":"write","path":"src/main.rs","content":"fn main() {}"}],"commands":[]}"#;
        let result = perspt_core::normalize::extract_and_deserialize::<ArtifactBundle>(json);
        assert!(result.is_ok());
        let (bundle, _method) = result.unwrap();
        assert_eq!(bundle.artifacts.len(), 1);
        assert!(bundle.validate().is_ok());
    }

    #[test]
    fn test_strict_json_layer_c_invalid_schema() {
        // Layer C: JSON parses but doesn't match ArtifactBundle schema
        let json = r#"{"foo": "bar"}"#;
        let result = perspt_core::normalize::extract_and_deserialize::<ArtifactBundle>(json);
        // extract_and_deserialize may fail at deserialization
        assert!(result.is_err());
    }

    #[test]
    fn test_tolerant_recovery_layer_d_file_markers() {
        // Layer D: extract_file_markers recovers artifacts from markdown
        let response = r#"
Here is the implementation:

### File: src/main.rs
```rust
fn main() {
    println!("Hello");
}
```

### File: src/lib.rs
```rust
pub fn greet() -> &'static str { "Hello" }
```
"#;
        let markers = perspt_core::normalize::extract_file_markers(response);
        assert_eq!(markers.len(), 2);
        assert_eq!(markers[0].path, Some("src/main.rs".to_string()));
        assert_eq!(markers[1].path, Some("src/lib.rs".to_string()));
        assert!(!markers[0].is_diff);
    }

    #[test]
    fn test_tolerant_recovery_layer_d_no_named_blocks() {
        // Layer D: unnamed code blocks produce None path (never invented)
        let response = "Here is some code:\n```rust\nfn foo() {}\n```\n";
        let markers = perspt_core::normalize::extract_file_markers(response);
        // Unnamed blocks don't produce markers with paths
        let named = markers.iter().filter(|m| m.path.is_some()).count();
        assert_eq!(named, 0);
    }

    #[test]
    fn test_path_normalization_layer_b() {
        // Layer B: path normalization strips backticks, quotes, markdown
        let normalized = perspt_core::path::normalize_artifact_path("`src/main.rs`").unwrap();
        assert_eq!(normalized, "src/main.rs");

        let normalized = perspt_core::path::normalize_artifact_path("'src/lib.rs'").unwrap();
        assert_eq!(normalized, "src/lib.rs");

        let normalized = perspt_core::path::normalize_artifact_path("**src/utils.rs**").unwrap();
        assert_eq!(normalized, "src/utils.rs");
    }

    #[test]
    fn test_empty_bundle_detection() {
        let bundle = ArtifactBundle {
            artifacts: vec![],
            commands: vec![],
        };
        assert!(bundle.artifacts.is_empty());
    }

    #[test]
    fn test_bundle_with_commands() {
        let json = r#"{"artifacts":[{"operation":"write","path":"src/main.rs","content":"fn main() {}"}],"commands":["cargo add serde"]}"#;
        let result = perspt_core::normalize::extract_and_deserialize::<ArtifactBundle>(json);
        assert!(result.is_ok());
        let (bundle, _) = result.unwrap();
        assert_eq!(bundle.commands.len(), 1);
        assert_eq!(bundle.commands[0], "cargo add serde");
    }

    #[test]
    fn test_layer_d_diff_markers() {
        let response = r#"
### Diff: src/main.rs
```diff
--- a/src/main.rs
+++ b/src/main.rs
@@ -1 +1 @@
-fn main() {}
+fn main() { println!("hello"); }
```
"#;
        let markers = perspt_core::normalize::extract_file_markers(response);
        assert!(!markers.is_empty());
        let first = &markers[0];
        assert_eq!(first.path, Some("src/main.rs".to_string()));
        assert!(first.is_diff);
    }

    #[test]
    fn test_no_structured_payload() {
        // A response with no JSON and no file markers
        let response = "I'm sorry, I can't help with that. Please try again.";
        let json_result =
            perspt_core::normalize::extract_and_deserialize::<ArtifactBundle>(response);
        assert!(json_result.is_err());
        let markers = perspt_core::normalize::extract_file_markers(response);
        assert!(markers.is_empty());
    }

    #[test]
    fn test_fenced_json_bundle_extraction() {
        // JSON bundle wrapped in markdown code fence
        let response = r#"Here is the bundle:
```json
{"artifacts":[{"operation":"write","path":"src/main.rs","content":"fn main() {}"}],"commands":[]}
```
"#;
        let result = perspt_core::normalize::extract_and_deserialize::<ArtifactBundle>(response);
        assert!(result.is_ok());
    }

    #[test]
    fn test_artifact_operation_paths() {
        let write = ArtifactOperation::Write {
            path: "src/main.rs".to_string(),
            content: "fn main() {}".to_string(),
        };
        assert_eq!(write.path(), "src/main.rs");

        let diff = ArtifactOperation::Diff {
            path: "src/lib.rs".to_string(),
            patch: "...".to_string(),
        };
        assert_eq!(diff.path(), "src/lib.rs");
    }
}