perspt-agent 0.6.6

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
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
//! Node assembly: graphs, capabilities, grants, and the coding contract.

use super::*;

pub(crate) fn promotion_manifest(
    recorder: &Psp9Recorder,
    workspace: &Path,
    candidate: &Path,
    paths: &[String],
) -> Result<Vec<serde_json::Value>> {
    let workspace_root = crate::promote::WorkspaceRoot::open(workspace)?;
    let candidate_root = crate::promote::WorkspaceRoot::open(candidate)?;
    let mut files = Vec::new();
    for relative in paths {
        let before = workspace_root.read_if_present(relative)?;
        let after = candidate_root.read_if_present(relative)?;
        let before_hash = before
            .as_deref()
            .map(|bytes| recorder.record_artifact(bytes, "application/octet-stream"))
            .transpose()?;
        let after_hash = after
            .as_deref()
            .map(|bytes| recorder.record_artifact(bytes, "application/octet-stream"))
            .transpose()?;
        files.push(serde_json::json!({
            "path": relative,
            "before_hash": before_hash,
            "after_hash": after_hash,
        }));
    }
    Ok(files)
}

/// Write-ahead promotion: record the intent, promote under the epoch
/// guard, then record the commit and completion.
pub(crate) fn commit_promotion(
    recorder: &Psp9Recorder,
    candidate: &CandidateWorkspace,
    node_id: &str,
    epoch: u64,
    state_root: &str,
    touched: &[String],
    working_dir: &Path,
) -> Result<Vec<String>> {
    let generation = candidate.node_generation();
    let promotion_key = format!("promote:{node_id}:{generation}");
    let promotion_files =
        promotion_manifest(recorder, working_dir, candidate.overlay_root(), touched)?;
    let promotion_intent = serde_json::json!({
        "idempotency_key": promotion_key,
        "node_id": node_id,
        "generation": generation,
        "authority_epoch": epoch,
        "workspace_root": working_dir.canonicalize()?.display().to_string(),
        "candidate_root": state_root,
        "files": promotion_files,
    });
    recorder.record_external_intent(&promotion_key, &promotion_intent)?;
    let promoted_paths =
        recorder
            .store
            .with_authority_epoch(&recorder.session_id, epoch, || candidate.promote())?;
    recorder.record_custom(
        "authority_epoch_effect_committed",
        serde_json::json!({
            "node_id": node_id,
            "generation": generation,
            "epoch": epoch,
        }),
    )?;
    recorder.complete_external_effect(
        &promotion_key,
        &serde_json::json!({"idempotency_key": promotion_key, "paths": promoted_paths}),
    )?;
    recorder.record_custom(
        "candidate_promoted",
        serde_json::json!({"node_id": node_id, "paths": promoted_paths}),
    )?;
    Ok(promoted_paths)
}

/// Session plumbing the recovery ladder threads through every rung.
pub(crate) struct LadderSession<'a> {
    pub recorder: &'a Psp9Recorder,
    pub session_id: &'a str,
    pub node_id: &'a str,
    pub scheduler: &'a mut Scheduler,
}

/// Level 4: the loop already restored the accepted state; revoke the
/// session's authority so nothing minted under this epoch can still
/// deliver. Exception: containment caused by exhausted provider transport
/// is an infrastructure outcome, not a governance anomaly — authority is
/// preserved so `perspt resume` can continue from the durable checkpoint
/// once the provider recovers.
pub(crate) fn contain_if_escalated(
    recorder: &Psp9Recorder,
    session_id: &str,
    attempt: &NodeAttempt,
) -> Result<()> {
    if !matches!(
        attempt.outcome.outcome,
        NodeTerminalOutcome::Escalated { .. }
    ) {
        return Ok(());
    }
    if attempt.outcome.contained_by_transport {
        recorder.record_custom(
            "containment_preserved_authority",
            serde_json::json!({
                "reason": "provider transport exhausted; resume remains viable",
            }),
        )?;
        return Ok(());
    }
    let epoch = recorder.store.revoke_authority(session_id)?;
    recorder.record_custom(
        "authority_epoch_revoked",
        serde_json::json!({"level": "contain", "new_epoch": epoch}),
    )?;
    Ok(())
}

/// Gate decisions an attempt consumed, for the shared non-replenishing pool.
pub(crate) fn spent_of(attempt: &NodeAttempt) -> u32 {
    attempt
        .outcome
        .trajectory
        .rejections_used
        .max(attempt.outcome.recovery_spent)
}

/// Swap the scheduler's running entry to the refined generation so its view
/// stays aligned with the graph revision (frees the old footprint, occupies
/// the new one, and records the dispatch).
pub(crate) fn redispatch_refined(
    recorder: &Psp9Recorder,
    scheduler: &mut Scheduler,
    revised: &WorkGraphRevision,
    node_id: &str,
    prior_generation: u32,
) -> Result<()> {
    scheduler.finish(node_id, prior_generation);
    let node = revised
        .node(node_id)
        .context("refined node missing from revision")?;
    scheduler.start(node, node_footprint(node));
    recorder.record_custom(
        "scheduler_dispatch",
        serde_json::json!({
            "node_id": node.node_id,
            "generation": node.generation,
            "parallel_slot": 0,
        }),
    )?;
    Ok(())
}

pub(crate) fn qualify_model(
    value: &str,
    config: &perspt_core::Config,
    portfolio: &perspt_core::ModelPortfolio,
) -> Result<ModelId> {
    if let Ok(model) = ModelId::from_str(value) {
        return Ok(model);
    }
    let ids = portfolio.provider_ids();
    let provider = config
        .provider
        .as_deref()
        .filter(|id| ids.iter().any(|configured| configured == id))
        .map(str::to_string)
        .or_else(|| (ids.len() == 1).then(|| ids[0].clone()))
        .context("bare model name is ambiguous; use provider::model")?;
    Ok(ModelId::new(provider, value))
}

pub(crate) fn initial_graph(node_id: &str, task: &str) -> Result<WorkGraphRevision> {
    let mut node = WorkNode::new(node_id, task, NodeClass::Implement);
    node.owner_domains = vec!["coding".into()];
    node.state = WorkNodeState::Ready;
    WorkGraphRevision::build(
        0,
        None,
        perspt_sdk::GraphRevisionReason::InitialPlan,
        vec![node],
        vec![],
    )
    .map_err(|e| anyhow::anyhow!(e.to_string()))
}

pub(crate) fn execution_revision(
    previous: &WorkGraphRevision,
    node_id: &str,
    state: WorkNodeState,
) -> Result<WorkGraphRevision> {
    let mut nodes = previous.nodes.clone();
    let node = nodes
        .iter_mut()
        .find(|node| node.node_id == node_id)
        .context("execution revision references an unknown node")?;
    node.state = state;
    WorkGraphRevision::build(
        previous.sequence + 1,
        Some(previous.revision_id.clone()),
        perspt_sdk::GraphRevisionReason::ExecutionUpdate,
        nodes,
        previous.edges.clone(),
    )
    .map_err(|error| anyhow::anyhow!(error.to_string()))
}

pub(crate) fn node_footprint(node: &WorkNode) -> Footprint {
    if node.output_targets.is_empty() {
        return Footprint::new().write(Resource::OpaqueWorkspace);
    }
    node.output_targets
        .iter()
        .fold(Footprint::new(), |footprint, path| {
            footprint.write(Resource::File(path.clone()))
        })
}

/// Resolve the explorer, adjudicator, and handoff role routes.
#[allow(clippy::type_complexity)]
pub(crate) fn resolve_role_routes(
    routes: &Psp9ModelRoutes,
    config: &perspt_core::Config,
    transport: &Arc<GenAiTransport>,
) -> Result<(Option<ModelId>, Option<ModelId>, Option<ModelId>)> {
    let explorer = resolve_role_route(
        routes.explorer.as_deref(),
        config.models.as_ref().and_then(|m| m.speculator.as_deref()),
        config,
        transport,
    )?;
    let adjudicator = resolve_role_route(
        routes.adjudicator.as_deref(),
        config
            .models
            .as_ref()
            .and_then(|m| m.adjudicator.as_deref()),
        config,
        transport,
    )?;
    let handoff = resolve_role_route(
        None,
        config.models.as_ref().and_then(|m| m.architect.as_deref()),
        config,
        transport,
    )?
    .filter(|candidate| transport.capabilities(candidate).tool_calling);
    Ok((explorer, adjudicator, handoff))
}

/// Resolve an optional role route (explicit flag first, then config), and
/// verify its provider eagerly so a typo fails before a session is created.
pub(crate) fn resolve_role_route(
    explicit: Option<&str>,
    configured: Option<&str>,
    config: &perspt_core::Config,
    transport: &Arc<GenAiTransport>,
) -> Result<Option<ModelId>> {
    let resolved = explicit
        .or(configured)
        .map(|value| qualify_model(value, config, transport.portfolio()))
        .transpose()?;
    if let Some(model) = &resolved {
        transport.portfolio().resolve(&model.provider)?;
    }
    Ok(resolved)
}

/// Evaluate the promotion proposal against all five clauses on the realized
/// witness. Returns whether promotion is certified; a denial is recorded.
#[allow(clippy::too_many_arguments)]
pub(crate) fn certify_promotion(
    recorder: &Psp9Recorder,
    node_id: &str,
    touched: &[String],
    realized: &perspt_sdk::CandidateStateWitness,
    capability: &Capability,
    contract: &CodingContract,
    barrier: &OperationalSafetyBarrier,
    kernel_state: &perspt_sdk::KernelState,
) -> Result<bool> {
    let mut state = kernel_state.clone();
    state.set_witness("__candidate_root", realized.state_root.clone());
    let generation = capability.node_generation;
    let mut proposal = perspt_sdk::EffectProposal::new(
        capability.holder.clone(),
        node_id,
        perspt_sdk::EffectKind::WriteArtifact,
    )
    .with_generation(generation)
    .with_risk_class(perspt_sdk::RiskClass::High)
    .with_idempotency_key(format!("promote:{node_id}:{generation}"));
    if let Some((first, rest)) = touched.split_first() {
        proposal = proposal
            .with_path(first.clone())
            .with_additional_paths(rest.to_vec());
    }
    let transition =
        perspt_sdk::CandidateTransition::new(proposal, realized.clone(), realized.clone());
    let witness = perspt_sdk::check_full_admissibility(
        &transition,
        std::slice::from_ref(capability),
        &state,
        Some(contract),
        Some(barrier),
        0.25,
    )
    .map_err(|e| anyhow::anyhow!("promotion kernel: {e}"))?;
    recorder.record_custom("promotion_admissibility", serde_json::to_value(&witness)?)?;
    if !witness.allows() || witness.profile != perspt_sdk::AdmissibilityProfile::SrbnCertified {
        recorder.record_custom(
            "promotion_denied",
            serde_json::json!({
                "node_id": node_id,
                "decision": format!("{:?}", witness.base.decision),
                "profile": format!("{:?}", witness.profile),
            }),
        )?;
        return Ok(false);
    }
    Ok(true)
}

/// Uniform delayed-audit funding (resolved decision 4): at cold start every
/// promoted candidate is audit-selected. The sample stays unlabeled until
/// `perspt audit` ingests the delayed verdict; only labeled samples count
/// toward the conformal floor.
/// Record the deterministic verifier suite's verdict beside the
/// adjudicator's (validator id "deterministic-suite"). `missed` at insert
/// time records the contemporaneous verdict ("did the suite flag this
/// candidate"); false negatives are computed later against the delayed
/// label by the estimator.
pub(crate) fn record_deterministic_verdict(
    recorder: &Psp9Recorder,
    candidate_id: &str,
    stratum: &str,
    hard_pass: bool,
) -> Result<()> {
    let evidence = serde_json::json!({"hard_pass": hard_pass});
    let evidence_hash =
        recorder.record_artifact(evidence.to_string().as_bytes(), "application/json")?;
    recorder.store.record_psp9_verdict(&Psp9VerdictRow {
        session_id: recorder.session_id.clone(),
        candidate_id: candidate_id.to_string(),
        validator_id: "deterministic-suite".into(),
        stratum: stratum.to_string(),
        missed: !hard_pass,
        unsafe_label: None,
        evidence_hash,
    })
}

/// `rho_eff` from labeled matched verdicts, only when certified (>= 20
/// matched labeled samples per pair, Hoeffding upper bounds).
pub(crate) fn certified_pairwise_risk(store: &SessionStore) -> Option<f64> {
    let rows = store.labeled_psp9_verdicts().ok()?;
    let records = verdict_records(&rows);
    if records.is_empty() {
        return None;
    }
    perspt_sdk::independence::compute(&records)
        .ok()
        .and_then(|stats| stats.rho_eff)
}

/// Convert labeled store rows into estimator records. The estimator's
/// `missed` is the *false negative* against the delayed label: the
/// validator passed a candidate later labeled unsafe. A stored row's
/// `missed` field is the contemporaneous verdict ("flagged fail").
pub(crate) fn verdict_records(rows: &[Psp9VerdictRow]) -> Vec<perspt_sdk::VerdictRecord> {
    rows.iter()
        .filter_map(|row| {
            let unsafe_label = row.unsafe_label?;
            let passed = !row.missed;
            Some(perspt_sdk::VerdictRecord::new(
                row.validator_id.clone(),
                row.candidate_id.clone(),
                passed && unsafe_label,
            ))
        })
        .collect()
}

pub(crate) fn record_promotion_sample(
    recorder: &Psp9Recorder,
    calibration: &CalibrationBinding,
    sample_id: &str,
) -> Result<()> {
    recorder.store.record_psp9_calibration_sample(
        &calibration.epoch_id,
        sample_id,
        1.0, // score definition v1: hard pass ⇒ V = 0 ⇒ 1/(1+V)
        None,
        true,
    )?;
    recorder.record_custom(
        "calibration_sample_recorded",
        serde_json::json!({
            "epoch_id": calibration.epoch_id,
            "sample_id": sample_id,
            "audit_selected": true,
            "labeled": false,
        }),
    )
}

/// The kernel's durable witnesses for one loop: authority epoch, graph
/// revision, and the wall clock (capability expiry fails closed without a
/// `__now` witness, so `expires_at`-bearing capabilities stay enforceable).
pub(crate) fn loop_kernel_state(
    grant_policy: &perspt_sdk::GrantPolicy,
    revision_id: &str,
) -> perspt_sdk::KernelState {
    let mut kernel_state = perspt_sdk::KernelState::new();
    kernel_state.set_witness(
        "__authority_epoch",
        grant_policy.authority_epoch.to_string(),
    );
    kernel_state.set_witness("__graph_revision", revision_id.to_string());
    let now_unix = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0);
    kernel_state.set_witness("__now", now_unix.to_string());
    kernel_state
}

/// Resolve, verify, and dedupe the sticky actuator fallback chain. Every
/// fallback must declare native tool calling (Gate U).
pub(crate) fn resolve_fallbacks(
    routes: &[String],
    model: &ModelId,
    config: &perspt_core::Config,
    transport: &Arc<GenAiTransport>,
) -> Result<Vec<ModelId>> {
    let mut fallback_models = Vec::new();
    for value in routes {
        let candidate = qualify_model(value, config, transport.portfolio())?;
        transport.portfolio().resolve(&candidate.provider)?;
        anyhow::ensure!(
            transport.capabilities(&candidate).tool_calling,
            "fallback route {candidate} does not declare native tool calling"
        );
        if candidate != *model && !fallback_models.contains(&candidate) {
            fallback_models.push(candidate);
        }
    }
    Ok(fallback_models)
}

/// The Refine rung, gated on failure class: a transport-contained attempt
/// is an infrastructure outage, not a capability failure — refining the
/// goal and opening forest branches against the same rate-limited or dead
/// route multiplies the retry storm for nothing, so the rung is skipped
/// (`None`) with a ledgered reason and only the Escalate rung (a different
/// route) may follow.
pub(crate) fn refine_rung(
    recorder: &Psp9Recorder,
    scheduler: &mut Scheduler,
    graph: &WorkGraphRevision,
    node_id: &str,
    generation: u32,
    goal: &str,
    attempt: &NodeAttempt,
) -> Result<Option<(WorkGraphRevision, String)>> {
    if attempt.outcome.contained_by_transport {
        recorder.record_custom(
            "recovery_rung_skipped",
            serde_json::json!({
                "level": "refine",
                "reason": "attempt was contained by transport exhaustion; \
                           branch search against the same route cannot help",
            }),
        )?;
        return Ok(None);
    }
    let (revised, refined_goal) = refine_node(recorder, graph, node_id, generation, goal, attempt)?;
    redispatch_refined(recorder, scheduler, &revised, node_id, generation)?;
    Ok(Some((revised, refined_goal)))
}

/// Level-2 graph refinement (Theorem 6): revise the running graph with the
/// exhausted attempt's evidence, producing the node's next generation and a
/// refined goal. The revision passes `WorkGraphRevision::revise`, so it is a
/// validated acyclic snapshot, never an in-place mutation.
pub(crate) fn refine_node(
    recorder: &Psp9Recorder,
    graph: &WorkGraphRevision,
    node_id: &str,
    generation: u32,
    goal: &str,
    attempt: &NodeAttempt,
) -> Result<(WorkGraphRevision, String)> {
    let trajectory = &attempt.outcome.trajectory;
    let refined_goal = format!(
        "{goal}\n\nThe previous governed attempt (generation {generation}) exhausted its \
         correction budget: best V = {best:.3} after {rejections} rejection(s) and \
         {denied} denied proposal(s). Decompose the change into smaller verified steps \
         and address the dominant failing verifier first.",
        best = trajectory.best_accepted_energy,
        rejections = trajectory.rejections_used,
        denied = attempt.outcome.projection.denied_proposals,
    );
    let mut node = graph
        .node(node_id)
        .context("refining an unknown node")?
        .clone();
    node.generation = generation + 1;
    node.goal = refined_goal.clone();
    node.state = WorkNodeState::Running;
    let evidence = vec![perspt_sdk::ResidualEventRef {
        residual_id: format!("gate:{node_id}:{generation}:budget-exhausted"),
        class: perspt_sdk::ResidualClass::BudgetExhausted,
        component: perspt_sdk::EnergyComponent::Log,
        weighted_energy: trajectory.best_accepted_energy,
    }];
    let revised = graph
        .revise(
            perspt_sdk::GraphRevisionReason::LocalRepair,
            &[perspt_sdk::GraphEdit::ReplaceNode { node }],
            evidence,
        )
        .map_err(|e| anyhow::anyhow!("graph refinement: {e}"))?;
    recorder.record_custom("graph_revision", serde_json::to_value(&revised)?)?;
    recorder.record_custom(
        "recovery_refined",
        serde_json::json!({
            "level": "refine",
            "node_id": node_id,
            "next_generation": generation + 1,
            "revision_id": revised.revision_id,
        }),
    )?;
    Ok((revised, refined_goal))
}

/// Effects that never enter a session grant implicitly, no matter what the
/// assembled catalog declares. Each needs its own explicit opt-in path
/// (approval mode, dedicated flag, or a future grant surface).
pub(crate) const WITHHELD_EFFECTS: &[EffectKind] = &[
    EffectKind::RunShell,
    EffectKind::GitWrite,
    EffectKind::NetworkFetch,
    EffectKind::MutateDependencies,
    EffectKind::SpawnAgent,
    EffectKind::UpdateGraph,
    EffectKind::UpdatePolicy,
];

/// Granting is policy × data: the effect set follows the assembled catalog
/// (so a registered tool family is grantable without editing this module),
/// minus the withheld set, plus any effect the user explicitly opted into
/// (e.g. `--allow-dependency-mutation`).
pub(crate) fn granted_effects(
    catalog: &dyn ToolCatalog,
    opted_in: &[EffectKind],
) -> Vec<EffectKind> {
    let mut effects = Vec::new();
    for entry in catalog.entries() {
        let withheld =
            WITHHELD_EFFECTS.contains(&entry.effect) && !opted_in.contains(&entry.effect);
        if withheld || effects.contains(&entry.effect) {
            continue;
        }
        effects.push(entry.effect);
    }
    effects
}

pub(crate) fn worker_capability(
    session_id: &str,
    graph_revision: &str,
    authority_epoch: u64,
    generation: u32,
    catalog: &dyn ToolCatalog,
    opted_in: &[EffectKind],
) -> Capability {
    let mut capability =
        Capability::new(ActorId::new("toolloop"), granted_effects(catalog, opted_in));
    capability.path_scope = vec![PathPattern("*".into())];
    capability.command_scope = inspection_command_scope();
    capability.max_calls = Some(100);
    capability.risk_budget = Some(RiskBudget::new("workspace-barrier", 2.0));
    // This capability authorizes only the disposable candidate overlay. The
    // separate promotion policy controls durable delivery to the workspace.
    capability.approval_policy = ApprovalPolicy::Auto;
    capability.session_id = session_id.into();
    capability.authority_epoch = authority_epoch;
    capability.graph_revision = graph_revision.into();
    capability.node_generation = generation;
    capability.role = CapabilityRole::Worker;
    capability
}

pub(crate) fn session_grant_policy(
    workspace: &Path,
    graph_revision: &str,
    persistent: bool,
    catalog: &dyn ToolCatalog,
    opted_in: &[EffectKind],
) -> Result<GrantPolicy> {
    let workspace_root = workspace.canonicalize()?.display().to_string();
    let policy_id = uuid::Uuid::new_v4().to_string();
    let signature_material = format!("{policy_id}:{workspace_root}:{graph_revision}:0");
    Ok(GrantPolicy {
        policy_id,
        workspace_root,
        effect_ceiling: granted_effects(catalog, opted_in),
        path_ceiling: vec![PathPattern("*".into())],
        command_ceiling: inspection_command_scope(),
        network_ceiling: Vec::new(),
        approval_ceiling: ApprovalPolicy::Ask,
        authority_epoch: 0,
        persistent,
        integrity_binding: format!(
            "ledger:{}",
            perspt_sdk::ledger::content_hash(signature_material.as_bytes())
        ),
    })
}

/// Declared node output targets as write-scope patterns; a directory
/// target (trailing `/`) covers its subtree.
pub(crate) fn write_scope_from_targets(targets: &[String]) -> Vec<PathPattern> {
    targets
        .iter()
        .map(|target| {
            if target.ends_with('/') {
                PathPattern(format!("{target}*"))
            } else {
                PathPattern(target.clone())
            }
        })
        .collect()
}

pub(crate) fn inspection_command_scope() -> Vec<CommandPattern> {
    [
        "rg", "grep", "find", "sort", "uniq", "wc", "comm", "cat", "head", "tail", "ls", "git",
        "sed", "awk",
    ]
    .into_iter()
    .map(|program| CommandPattern(program.into()))
    .collect()
}

pub(crate) struct CodingContract {
    pub(crate) graph_revision: String,
    pub(crate) node_id: String,
    pub(crate) generation: u32,
    pub(crate) policy: perspt_policy::engine::PolicyEngine,
}

impl ContractEvaluator for CodingContract {
    fn evaluate(&self, transition: &CandidateTransition) -> ContractWitness {
        let proposal = &transition.proposal;
        // The policy engine matches text patterns against real command lines,
        // so it must see the canonical rendering, never the Debug form.
        let policy_ok = proposal.command.as_ref().is_none_or(|command| {
            matches!(
                self.policy.evaluate(&command.command_line()),
                perspt_policy::engine::PolicyDecision::Allow
            )
        });
        let scope_valid = transition
            .after
            .canonical_scope
            .iter()
            .all(|path| !path.starts_with('/') && !path.split('/').any(|part| part == ".."));
        let ok = proposal.node_id == self.node_id
            && proposal.generation == self.generation
            && transition.before.graph_revision == self.graph_revision
            && transition.after.graph_revision == self.graph_revision
            && transition.before.node_generation == self.generation
            && transition.after.node_generation == self.generation
            && scope_valid
            && policy_ok
            && !matches!(
                proposal.effect,
                EffectKind::UpdateGraph | EffectKind::UpdatePolicy
            )
            && !matches!(
                proposal.effect,
                EffectKind::RunShell | EffectKind::NetworkFetch
            );
        ContractWitness {
            ok,
            policy_version: "coding-contract-v1".into(),
            evidence_refs: vec![
                format!("before:{}", transition.before.state_root),
                format!("after:{}", transition.after.state_root),
                format!("revision:{}", self.graph_revision),
            ],
        }
    }
}

/// Load the newest durable candidate checkpoint: its control frame and the
/// seed files fetched from content-addressed artifacts. Refuses when the
/// session's durable authority epoch no longer matches the checkpoint's
/// (revocation invalidates resumed sessions).
#[derive(Clone)]
pub(crate) struct CandidateSeed {
    pub(crate) expected_state_root: String,
    pub(crate) canonical_scope: Vec<String>,
    pub(crate) files: Vec<crate::toolloop::SeedFile>,
    pub(crate) conversation: Conversation,
    /// Per-message birth dependencies parallel to `conversation` (Gate
    /// AF); empty for files-only seeds and pre-provenance checkpoints.
    pub(crate) birth_deps: Vec<perspt_sdk::prompt::StateDependency>,
    pub(crate) activated_tools: Vec<String>,
    /// True when the files are inherited staged predecessor state (system
    /// 22): restored without entering the promotable set, so the node
    /// exports only its own work. A node's own checkpoint restores as
    /// promotable (false).
    pub(crate) inherited: bool,
}

struct DurableCandidateState {
    state_root: String,
    control: perspt_sdk::ControlFrame,
    conversation: Conversation,
    birth_deps: Vec<perspt_sdk::prompt::StateDependency>,
    canonical_scope: Vec<String>,
    files: Vec<crate::toolloop::DurableSeedFile>,
}

/// Select the last candidate event in ledger order. The side-table index
/// may lag, timestamp-tie, or end in a different checkpoint kind.
fn latest_candidate_state(rows: &[perspt_store::Psp9LedgerRow]) -> Result<DurableCandidateState> {
    let mut latest = None;
    for row in rows {
        let Ok(perspt_sdk::LedgerEvent::Custom { kind, payload }) =
            serde_json::from_str(&row.event_json)
        else {
            continue;
        };
        if kind != "tool_loop" {
            continue;
        }
        if let LoopEvent::DurableCandidateCheckpoint {
            state_root,
            control,
            conversation,
            birth_deps,
            canonical_scope,
            files,
            ..
        } = crate::toolloop::decode_tool_loop(&payload)?.event
        {
            latest = Some(DurableCandidateState {
                state_root,
                control,
                conversation,
                birth_deps,
                canonical_scope,
                files,
            });
        }
    }
    latest.context("session has no durable candidate checkpoint in its verified ledger")
}

pub(crate) fn load_candidate_checkpoint(
    recorder: &Psp9Recorder,
    session_id: &str,
) -> Result<(perspt_sdk::ControlFrame, CandidateSeed)> {
    // The hash-chained ledger is the resume authority. The checkpoint table
    // is only a query accelerator and can lag the event (crash between the
    // two writes), tie on timestamps, or contain a newer context checkpoint.
    // Selecting the last durable candidate event in ledger order also makes
    // parallel-node checkpoint ordering unambiguous.
    let rows = recorder.store.get_psp9_events(session_id)?;
    let durable = latest_candidate_state(&rows)?;
    let DurableCandidateState {
        state_root,
        control,
        conversation,
        birth_deps,
        canonical_scope,
        files: file_handles,
    } = durable;
    anyhow::ensure!(
        conversation.unresolved_call_ids() == control.unresolved_call_ids,
        "checkpoint conversation does not match its unresolved-call control frame"
    );
    anyhow::ensure!(
        control.event_schema_version == perspt_sdk::CONVERSATION_EVENT_SCHEMA_VERSION,
        "checkpoint conversation event schema is unsupported"
    );
    anyhow::ensure!(
        state_root == control.accepted_state_root,
        "checkpoint state root does not match its control frame; refusing resume"
    );
    // Gate O: the checkpointed conversation clone is only the cheap resume
    // path — it must be *derivable from the ledger*. Refold the recorded
    // deltas and refuse resume unless the fold reproduces both the rolling
    // digest the control frame committed to and the clone itself.
    let folded = crate::toolloop::refold_session_context(&rows, &control.projection_digest)?
        .context("no ledger fold reaches the checkpoint digest; refusing resume")?;
    anyhow::ensure!(
        folded.conversation() == &conversation,
        "checkpoint conversation is not derivable from the recorded deltas; refusing resume"
    );
    let folded_tools: std::collections::BTreeSet<_> =
        folded.activated_tools().iter().cloned().collect();
    let control_tools: std::collections::BTreeSet<_> =
        control.activated_tools.iter().cloned().collect();
    anyhow::ensure!(
        folded_tools == control_tools && control_tools.len() == control.activated_tools.len(),
        "checkpoint activated tools are not derivable from the recorded deltas; refusing resume"
    );
    anyhow::ensure!(
        birth_deps.is_empty() || birth_deps.len() == conversation.messages().len(),
        "checkpoint birth provenance length does not match its conversation; refusing resume"
    );
    let current_epoch = recorder.store.authority_epoch(session_id)?;
    anyhow::ensure!(
        control.authority_epoch == current_epoch,
        "checkpoint is bound to authority epoch {} but the durable epoch is {}; \
         the session's authority was revoked",
        control.authority_epoch,
        current_epoch
    );
    let seed = CandidateSeed {
        inherited: false,
        expected_state_root: state_root,
        canonical_scope,
        files: load_seed_files(recorder, file_handles)?,
        conversation,
        birth_deps,
        activated_tools: control.activated_tools.clone(),
    };
    Ok((control, seed))
}

/// Export the previous attempt's best accepted state as a seed for the
/// next ladder rung, so recovery continues from the best measured state
/// instead of re-paying the whole cost (Paper III restore-best). `None`
/// when the attempt accepted nothing. The seed carries files only — the
/// next rung starts a fresh conversation around its refined goal.
pub(crate) async fn seed_from_attempt(
    recorder: &Psp9Recorder,
    node_id: &str,
    attempt: &NodeAttempt,
) -> Result<Option<CandidateSeed>> {
    let files = attempt.candidate.export_accepted().await?;
    if files.is_empty() {
        return Ok(None);
    }
    let checkpoint = attempt.candidate.checkpoint(&[]).await?;
    recorder.record_custom(
        "ladder_reseeded",
        serde_json::json!({
            "node_id": node_id,
            "files": files.len(),
            "state_root": checkpoint.witness.state_root,
        }),
    )?;
    Ok(Some(CandidateSeed {
        inherited: false,
        expected_state_root: checkpoint.witness.state_root,
        canonical_scope: checkpoint.witness.canonical_scope.clone(),
        files,
        conversation: Conversation::default(),
        birth_deps: Vec::new(),
        activated_tools: Vec::new(),
    }))
}

/// Rebuild an accepted candidate state from a durable checkpoint seed and
/// verify the restored state root matches it exactly.
pub(crate) async fn restore_seed(
    candidate: &CandidateWorkspace,
    seed: Option<&CandidateSeed>,
) -> Result<()> {
    let Some(seed) = seed else {
        return Ok(());
    };
    if seed.inherited {
        candidate.restore_seeded(&seed.files)?;
    } else {
        candidate.restore_exported(&seed.files)?;
    }
    let restored = candidate.checkpoint(&seed.canonical_scope).await?;
    anyhow::ensure!(
        restored.witness.state_root == seed.expected_state_root,
        "restored candidate state does not match its durable checkpoint"
    );
    Ok(())
}

/// Rehydrate checkpointed seed files from the content-addressed artifact
/// store, verifying every artifact against its recorded hash.
pub(crate) fn load_seed_files(
    recorder: &Psp9Recorder,
    file_handles: Vec<crate::toolloop::DurableSeedFile>,
) -> Result<Vec<crate::toolloop::SeedFile>> {
    let load = |handle: Option<String>, label: &str| -> Result<Option<Vec<u8>>> {
        let Some(handle) = handle else {
            return Ok(None);
        };
        let bytes = recorder
            .store
            .get_psp9_artifact(&handle)?
            .with_context(|| format!("missing {label} checkpoint artifact {handle}"))?;
        anyhow::ensure!(
            perspt_sdk::content_hash(&bytes) == handle,
            "{label} checkpoint artifact hash mismatch"
        );
        Ok(Some(bytes))
    };
    let mut seed = Vec::with_capacity(file_handles.len());
    for durable in file_handles {
        seed.push(crate::toolloop::SeedFile {
            path: durable.path,
            content: load(durable.content_artifact, "content")?,
            source_preimage: load(durable.source_preimage_artifact, "source pre-image")?,
        });
    }
    Ok(seed)
}

/// Recover the exact immutable graph revision named by the durable control
/// frame. Resume mints fresh authority against it instead of fabricating an
/// unrelated graph root.
pub(crate) fn resumed_running_graph(
    recorder: &Psp9Recorder,
    revision_id: &str,
    node_id: &str,
    generation: u32,
) -> Result<WorkGraphRevision> {
    let mut recovered = None;
    for row in recorder.store.get_psp9_events(&recorder.session_id)? {
        let event: LedgerEvent = serde_json::from_str(&row.event_json)?;
        if let LedgerEvent::Custom { kind, payload } = event {
            if kind == "graph_revision" {
                let graph: WorkGraphRevision = serde_json::from_value(payload)?;
                if graph.revision_id == revision_id {
                    recovered = Some(graph);
                    break;
                }
            }
        }
    }
    let graph = recovered.with_context(|| {
        format!("checkpoint graph revision {revision_id} is absent from the durable ledger")
    })?;
    let node = graph
        .node(node_id)
        .with_context(|| format!("checkpoint graph has no node {node_id}"))?;
    anyhow::ensure!(
        node.generation == generation && node.state == WorkNodeState::Running,
        "checkpoint graph node binding does not match the control frame"
    );
    recorder.record_custom(
        "graph_revision_resumed",
        serde_json::json!({"revision_id": revision_id}),
    )?;
    Ok(graph)
}

/// Compile and ledger the worker's prompt invocation through the SDK
/// compiler (PSP-10 systems 23–24): the platform envelope for the resolved
/// route and dialect, plus the domain's own session-bootstrap stage (empty
/// when the domain contributes none). Both programs and the invocation are
/// recorded before the loop runs (Gate Z).
pub(crate) fn worker_envelope(
    recorder: &Psp9Recorder,
    domain: &Arc<dyn AgentDomainPackage>,
    route: &perspt_sdk::prompt::PromptRoute,
    dialect: &perspt_sdk::prompt::ModelDialect,
    tool_spec_hash: &str,
    overrides: &perspt_core::prompts::SectionOverrides,
) -> Result<crate::toolloop::PromptEnvelope> {
    let stage = perspt_core::prompts::PlatformPromptLibrary::session_bootstrap(
        &domain.domain_id().0,
        overrides,
    )
    .map_err(|e| anyhow::anyhow!("session bootstrap prompt: {e}"))?;
    // The domain's same-stage sections are static per session; render once
    // so the loop can recompile per call without the domain package.
    let mut domain_sections = Vec::new();
    for template in domain
        .prompt_library()
        .stage_templates(stage.stage.dir_name())
    {
        domain_sections.push(
            template
                .render(&std::collections::BTreeMap::new())
                .map_err(|e| anyhow::anyhow!("domain section: {e}"))?,
        );
    }
    let invocation = perspt_core::prompts::compile_invocation(
        &stage,
        &domain_sections,
        route,
        dialect,
        tool_spec_hash,
    )
    .map_err(|e| anyhow::anyhow!("worker prompt invocation: {e}"))?;
    recorder.record_prompt_program(&invocation.platform)?;
    if !invocation.domain.messages.is_empty() {
        recorder.record_prompt_program(&invocation.domain)?;
    }
    recorder.record_prompt_invocation("worker", 0, &invocation)?;
    Ok(crate::toolloop::PromptEnvelope {
        text: invocation.platform.system_text(),
        invocation_digest: invocation.invocation_digest.clone(),
        manifest_digest: perspt_core::prompts::PlatformPromptLibrary::manifest().digest(),
        stage: Some(stage),
        domain_sections,
        invocation: Some(invocation),
    })
}

/// The immutable calibration epoch this run is bound to.
#[derive(Debug, Clone)]
pub(crate) struct CalibrationBinding {
    pub(crate) epoch_id: String,
    pub(crate) stratum: String,
    pub(crate) state: String,
    pub(crate) threshold: Option<f64>,
}

/// Everything `conclude_run` needs to decide a node's terminal fate.
pub(crate) struct ConcludeContext<'a> {
    pub(crate) recorder: &'a Psp9Recorder,
    pub(crate) candidate: &'a CandidateWorkspace,
    pub(crate) node_id: &'a str,
    pub(crate) task: &'a str,
    pub(crate) grant_policy: &'a GrantPolicy,
    pub(crate) capability: &'a Capability,
    pub(crate) contract: &'a CodingContract,
    pub(crate) barrier: &'a OperationalSafetyBarrier,
    pub(crate) kernel_state: &'a perspt_sdk::KernelState,
    pub(crate) loop_outcome: &'a NodeTerminalOutcome,
    pub(crate) calibration: &'a CalibrationBinding,
}

/// The governed surfaces assembled for one node run.
pub(crate) struct NodeAssembly {
    pub(crate) catalog: StaticCatalog,
    pub(crate) grant_policy: GrantPolicy,
    pub(crate) capability: Capability,
    pub(crate) contract: CodingContract,
    pub(crate) barrier: OperationalSafetyBarrier,
    pub(crate) cadence: perspt_sdk::VerificationCadence,
    pub(crate) energy: perspt_sdk::EnergyModel,
    pub(crate) calibration: CalibrationBinding,
}

/// A node attempt prepared before any workspace exists: the assembled
/// surfaces, the compiled prompt envelope, and the kernel state. Built
/// exactly once per attempt; the search forest derives exact no-good
/// components from it before admitting the fork (Gate AB).
pub(crate) struct PreparedAttempt {
    pub(crate) assembly: NodeAssembly,
    pub(crate) envelope: crate::toolloop::PromptEnvelope,
    pub(crate) kernel_state: perspt_sdk::KernelState,
}

/// One completed governed attempt at a node generation.
pub(crate) struct NodeAttempt {
    pub(crate) outcome: crate::toolloop::LoopOutcome,
    pub(crate) candidate: CandidateWorkspace,
    pub(crate) assembly: NodeAssembly,
    pub(crate) kernel_state: perspt_sdk::KernelState,
}

/// Run the loop, re-entering a seeded conversation when one exists: a
/// files-only seed restores candidate state but starts a fresh
/// conversation around the goal.
pub(crate) async fn run_seeded(
    tool_loop: crate::toolloop::ToolLoop<'_>,
    goal: &str,
    seed: Option<&CandidateSeed>,
) -> Result<crate::toolloop::LoopOutcome> {
    match seed {
        Some(seed) if !seed.conversation.messages().is_empty() => {
            let mut tool_loop = tool_loop;
            tool_loop.resumed_birth_deps = seed.birth_deps.clone();
            tool_loop
                .run_with_conversation(
                    goal,
                    Some(seed.conversation.clone()),
                    seed.activated_tools.clone(),
                )
                .await
        }
        _ => tool_loop.run(goal).await,
    }
}