perspt-coding 0.6.6

Coding domain package for the Perspt SRBN agent SDK: residual schema, energy model, and correction directions for Rust, Python, and TypeScript (PSP-8)
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
//! # Perspt Coding Domain Package
//!
//! `perspt-coding` is the first domain package built on [`perspt_sdk`] (PSP-8).
//! It exercises the SDK's Phase-0/1 contracts with a real consumer: it declares
//! the coding residual schema, supplies the coding [`EnergyModel`] (weights,
//! `rho_gate`, tolerance, correction budget), and maps dominant residuals into
//! coding correction directions.
//!
//! The coding domain operates on discrete verifier residuals (compiler, LSP,
//! AST, tests) and exposes no continuous embedding-space coordinate, so its
//! analytic constants `alpha, beta, delta, L, eta` remain `NotClaimed`; only the
//! measured discrete gate and the spectral `mu` apply.
//!
//! Language adapters (Rust, Python, TypeScript) will grow into full SDK
//! verifier-suite providers in later phases; this crate currently provides the
//! domain-level residual schema, energy model, and Rust correction mappers for
//! the unresolved-import / missing-module cases (PSP-8 Reference Implementation
//! step 10).

#![forbid(unsafe_code)]

pub mod barrier;
pub mod diag;
pub mod lang;
pub mod prompts;
pub mod registry;
pub mod runtime;
pub mod symbols;

pub use barrier::OperationalSafetyBarrier;
pub use registry::{CodingAdapterRegistry, LanguageId};
pub use runtime::{crash_marker, SmokeInvocation};
pub use symbols::{defined_symbols, expected_symbols};

use perspt_sdk::{
    AgentDomainPackage, BarrierChannel, BarrierSpec, CorrectionDirection, DomainDetection,
    DomainId, DomainScope, EnergyComponent, EnergyModel, HardGatePolicy, ResidualClass,
    ResidualEvent, ResidualSchema, ResidualWeight, SafetyBarrierDisposition, StabilityClaim,
    VerificationCadence, VerifierSuiteSpec, WorkspaceSnapshot,
};

/// The coding domain package.
#[derive(Debug, Clone, Default)]
pub struct CodingDomain;

impl CodingDomain {
    pub fn new() -> Self {
        Self
    }

    /// The residual classes the coding domain can emit.
    fn classes() -> Vec<ResidualClass> {
        vec![
            ResidualClass::Syntax,
            ResidualClass::Type,
            ResidualClass::Build,
            ResidualClass::TestFailure,
            ResidualClass::Lint,
            ResidualClass::Format,
            ResidualClass::Runtime,
            ResidualClass::Dependency,
            ResidualClass::Manifest,
            ResidualClass::ImportGraph,
            ResidualClass::SymbolMismatch,
            ResidualClass::InterfaceMismatch,
            ResidualClass::OwnershipViolation,
            ResidualClass::Policy,
            ResidualClass::Regression,
            ResidualClass::SensorUnavailable,
            ResidualClass::ToolFailure,
            ResidualClass::SheafInconsistency,
        ]
    }
}

impl AgentDomainPackage for CodingDomain {
    fn domain_id(&self) -> DomainId {
        DomainId::new("coding")
    }

    fn detect(&self, workspace: &WorkspaceSnapshot) -> DomainDetection {
        let mut evidence = Vec::new();
        for marker in ["Cargo.toml", "pyproject.toml", "package.json", "go.mod"] {
            if workspace.has_file_named(marker) {
                evidence.push(format!("found {marker}"));
            }
        }
        let activated = !evidence.is_empty();
        DomainDetection {
            domain: self.domain_id(),
            activated,
            confidence: if activated { 0.95 } else { 0.0 },
            evidence,
        }
    }

    fn residual_schema(&self, _scope: &DomainScope) -> ResidualSchema {
        ResidualSchema::new(Self::classes())
    }

    fn energy_model(&self, scope: &DomainScope) -> EnergyModel {
        use EnergyComponent::*;
        use ResidualClass::*;
        // Compiler/type errors weigh heavily (they block everything downstream);
        // structural and behavioral residuals weigh moderately; degraded
        // sensors are V_boot. Every class carries an explicit weight — no class
        // defaults to an implicit weight of 1.
        let weights = vec![
            ResidualWeight::new(Syntax, Syn, 4.0).with_hard_threshold(0.0),
            ResidualWeight::new(Type, Syn, 3.0).with_hard_threshold(0.0),
            ResidualWeight::new(Build, Syn, 3.0).with_hard_threshold(0.0),
            ResidualWeight::new(ImportGraph, Str, 2.0),
            ResidualWeight::new(SymbolMismatch, Str, 2.0),
            ResidualWeight::new(InterfaceMismatch, Str, 2.5),
            ResidualWeight::new(OwnershipViolation, Str, 2.0),
            ResidualWeight::new(Policy, Str, 1.0),
            ResidualWeight::new(Dependency, Str, 1.5),
            ResidualWeight::new(Manifest, Str, 1.5),
            ResidualWeight::new(Lint, Str, 0.5),
            ResidualWeight::new(Format, Str, 0.25),
            ResidualWeight::new(TestFailure, Log, 2.0),
            ResidualWeight::new(Runtime, Log, 2.0),
            ResidualWeight::new(Regression, Log, 3.0),
            ResidualWeight::new(SensorUnavailable, Boot, 1.0),
            ResidualWeight::new(ToolFailure, Boot, 1.0),
            ResidualWeight::new(SheafInconsistency, Sheaf, 2.0),
        ];

        let mut model = EnergyModel::new("coding", 0.5).with_correction_budget(4);
        model.residual_weights = weights;
        model.energy_tolerance = 0.0;
        // The coding domain is measured-only: analytic constants are NotClaimed.
        model.stability_claim = Some(StabilityClaim::not_claimed(format!(
            "coding scope: {}",
            scope.label
        )));
        model
    }

    fn correction_directions(&self, residuals: &[ResidualEvent]) -> Vec<CorrectionDirection> {
        // The two correction systems are one (PSP-10 system 26): the
        // language adapter identified by the residual's sensor answers
        // first with its richer per-language arms; the class-only mapping
        // is the fallback for language-neutral residuals.
        let registry = crate::CodingAdapterRegistry::with_builtins();
        residuals
            .iter()
            .filter_map(|residual| {
                language_for_sensor(&residual.sensor.id)
                    .and_then(|language| registry.get(&language))
                    .and_then(|adapter| adapter.correction_for(residual))
                    .or_else(|| correction_for(residual))
            })
            .collect()
    }

    fn correction_packet(
        &self,
        residuals: &[ResidualEvent],
    ) -> Option<perspt_sdk::CorrectionPacket> {
        build_correction_packet(self, residuals)
    }

    fn tool_entries(&self, _scope: &DomainScope) -> Vec<perspt_sdk::ToolEntry> {
        // The base catalog's run_test / run_build / run_formatter entries are
        // bound to concrete commands by the plugin registry at catalog
        // assembly; the coding domain contributes no extra entries yet.
        Vec::new()
    }

    fn hard_gate_policy(&self, _scope: &DomainScope) -> HardGatePolicy {
        HardGatePolicy {
            required_stages: vec!["syntax".into(), "build".into(), "test".into()],
        }
    }

    fn verifier_suite(&self, _scope: &DomainScope) -> VerifierSuiteSpec {
        VerifierSuiteSpec {
            stages: vec![
                "syntax".into(),
                "build".into(),
                "test".into(),
                "lint".into(),
            ],
            cadence: VerificationCadence::default(),
        }
    }

    fn safety_barrier(&self, _scope: &DomainScope) -> SafetyBarrierDisposition {
        // The versioned operational safety channels of PSP-9 system 12.
        // Correctness evidence (compiler errors, test failures) stays in V;
        // it is never duplicated into h.
        SafetyBarrierDisposition::Registered(BarrierSpec {
            channels: [
                "protected-path-modification",
                "sandbox-escape",
                "secret-exposure",
                "unapproved-network-reachability",
                "dependency-policy-violation",
                "resource-limits",
            ]
            .iter()
            .map(|name| BarrierChannel {
                name: (*name).to_string(),
                policy_version: "1".to_string(),
            })
            .collect(),
        })
    }
}

/// Map a residual's sensor identity to the language adapter that owns it.
fn language_for_sensor(sensor_id: &str) -> Option<crate::LanguageId> {
    match sensor_id {
        "rustc" | "cargo-test" => Some(crate::LanguageId::new("rust")),
        "ty" | "pyright" | "pytest" | "python-check" => Some(crate::LanguageId::new("python")),
        "tsc" => Some(crate::LanguageId::new("typescript")),
        _ => None,
    }
}

/// Fold all verifier residuals into one coherent typed correction packet
/// (PSP-10 system 26). Every direction participates — the historic
/// first-direction-only flattening is gone — and paths, symbols, spans,
/// and rationale survive to the model.
/// Fold every residual's structured evidence into the packet's diagnostic
/// list and affected set.
fn fold_evidence(
    residuals: &[ResidualEvent],
) -> (
    Vec<perspt_sdk::StructuredDiagnosticRef>,
    perspt_sdk::AffectedSet,
) {
    let mut diagnostics = Vec::new();
    let mut affected = perspt_sdk::AffectedSet::default();
    for residual in residuals {
        if let Some(refs) = residual.evidence.structured.as_ref().and_then(|value| {
            serde_json::from_value::<Vec<perspt_sdk::StructuredDiagnosticRef>>(value.clone()).ok()
        }) {
            for item in &refs {
                if let (Some(path), Some(line)) = (&item.path, item.line) {
                    affected
                        .spans
                        .push(format!("{path}:{line}:{}", item.column.unwrap_or(1)));
                }
                if residual.class == ResidualClass::TestFailure {
                    if let Some(test) = &item.code {
                        affected.tests.push(test.clone());
                    }
                }
            }
            diagnostics.extend(refs);
        }
        affected
            .paths
            .extend(residual.affected_paths.iter().cloned());
        affected
            .symbols
            .extend(residual.affected_symbols.iter().cloned());
    }
    affected.paths.sort();
    affected.paths.dedup();
    (diagnostics, affected)
}

fn build_correction_packet(
    domain: &CodingDomain,
    residuals: &[ResidualEvent],
) -> Option<perspt_sdk::CorrectionPacket> {
    let dominant = residuals
        .iter()
        .filter(|residual| residual.class != ResidualClass::SensorUnavailable)
        .max_by(|a, b| a.score.total_cmp(&b.score))?;
    let (diagnostics, affected) = fold_evidence(residuals);
    let operators: Vec<perspt_sdk::CorrectionOperator> = domain
        .correction_directions(residuals)
        .into_iter()
        .map(|direction| perspt_sdk::CorrectionOperator {
            operator_id: direction.direction_id.clone(),
            instruction: direction.instruction.clone(),
            addresses: direction.addresses,
            rationale: direction.rationale.clone(),
        })
        .collect();
    let uncertainty: Vec<perspt_sdk::MissingSensorDecl> = residuals
        .iter()
        .filter(|residual| residual.class == ResidualClass::SensorUnavailable)
        .map(|residual| perspt_sdk::MissingSensorDecl {
            sensor: residual.sensor.id.clone(),
            reason: residual.evidence.summary.clone(),
        })
        .collect();
    if operators.is_empty() && diagnostics.is_empty() {
        return None;
    }
    let member_count = dominant
        .evidence
        .structured
        .as_ref()
        .and_then(|value| value.as_array().map(|items| items.len() as u32))
        .unwrap_or(1);
    Some(perspt_sdk::CorrectionPacket {
        dominant_cluster: perspt_sdk::ResidualClusterRef {
            cluster_id: dominant.residual_id.clone(),
            class: dominant.class,
            root_cause: dominant.evidence.summary.clone(),
            member_count,
            magnitude: dominant.score,
        },
        diagnostics,
        affected,
        operators,
        expected_footprint: perspt_sdk::FootprintSpec::new(Vec::new()),
        follow_up_stages: Vec::new(),
        no_goods: Vec::new(),
        uncertainty,
    })
}

/// Map a single residual to a coding correction direction, or `None` when there
/// is no honest direction (the runtime then escalates rather than retrying
/// blindly).
fn correction_for(residual: &ResidualEvent) -> Option<CorrectionDirection> {
    match residual.class {
        ResidualClass::ImportGraph => {
            // Rust unresolved-import / missing-module direction (PSP-8 ref step 10).
            let symbol = residual
                .affected_symbols
                .first()
                .map(|s| s.name.clone())
                .unwrap_or_else(|| "the missing item".to_string());
            Some(
                CorrectionDirection::new(
                    ResidualClass::ImportGraph,
                    format!(
                        "resolve the unresolved import for `{symbol}`: add the missing `use` path \
                         or declare the missing `mod`, do not regenerate unrelated code"
                    ),
                )
                .with_paths(residual.affected_paths.clone())
                .with_rationale(
                    "unresolved imports are structural; the fix is an import/module \
                     declaration, not a behavioral rewrite",
                ),
            )
        }
        ResidualClass::Type => Some(
            CorrectionDirection::new(
                ResidualClass::Type,
                "reconcile the type mismatch at the reported span; adjust the expression or the \
                 declared signature, keeping the public interface stable",
            )
            .with_paths(residual.affected_paths.clone()),
        ),
        ResidualClass::Dependency | ResidualClass::Manifest => Some(
            CorrectionDirection::new(
                residual.class,
                "repair the dependency/manifest: add or pin the missing crate/package and sync \
                 the lockfile through an approved dependency-mutation effect",
            )
            .with_paths(residual.affected_paths.clone()),
        ),
        ResidualClass::TestFailure => Some(
            CorrectionDirection::new(
                ResidualClass::TestFailure,
                "address the failing test by fixing the implementation it attributes to; do not \
                 weaken or delete the assertion",
            )
            .with_paths(residual.affected_paths.clone()),
        ),
        // No honest direction for degraded sensors or pure tool failures: these
        // are bootstrap problems the runtime escalates, never a code retry.
        ResidualClass::SensorUnavailable | ResidualClass::ToolFailure => None,
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use perspt_sdk::{score_candidate, IndependenceRoute, ResidualSeverity, SensorRef, SymbolRef};

    fn lsp_import_residual() -> ResidualEvent {
        let mut r = ResidualEvent::new(
            "n1",
            0,
            ResidualClass::ImportGraph,
            ResidualSeverity::Error,
            1.0,
            SensorRef::new("rust-analyzer", IndependenceRoute::Lsp),
        )
        .unwrap();
        r.affected_symbols = vec![SymbolRef {
            name: "Bar".into(),
            container: Some("crate::foo".into()),
        }];
        r.affected_paths = vec!["src/main.rs".into()];
        r
    }

    #[test]
    fn detects_coding_domain_from_cargo_toml() {
        let domain = CodingDomain::new();
        let ws = WorkspaceSnapshot::new("/repo", vec!["Cargo.toml".into(), "src/main.rs".into()]);
        let detection = domain.detect(&ws);
        assert!(detection.activated);
        assert_eq!(detection.domain, DomainId::new("coding"));
    }

    #[test]
    fn energy_model_validates_and_is_measured_only() {
        let domain = CodingDomain::new();
        let model = domain.energy_model(&DomainScope::default());
        assert!(model.validate().is_ok());
        let claim = model.stability_claim.unwrap();
        assert!(
            !claim.claims_floor(),
            "coding domain must remain NotClaimed"
        );
    }

    #[test]
    fn rust_unresolved_import_yields_import_direction_not_retry() {
        let domain = CodingDomain::new();
        let directions = domain.correction_directions(&[lsp_import_residual()]);
        assert_eq!(directions.len(), 1);
        assert_eq!(directions[0].addresses, ResidualClass::ImportGraph);
        assert!(directions[0].instruction.contains("Bar"));
        assert!(directions[0].instruction.contains("use"));
    }

    #[test]
    fn degraded_sensor_has_no_correction_direction() {
        let domain = CodingDomain::new();
        let r = ResidualEvent::new(
            "n1",
            0,
            ResidualClass::SensorUnavailable,
            ResidualSeverity::Blocking,
            1.0,
            SensorRef::new("cargo", IndependenceRoute::DeterministicTool),
        )
        .unwrap();
        assert!(domain.correction_directions(&[r]).is_empty());
    }

    #[test]
    fn coding_energy_model_scores_real_residuals() {
        let domain = CodingDomain::new();
        let model = domain.energy_model(&DomainScope::default());
        // ImportGraph weight 2.0, score 1.0 -> 2.0 * 1^2 = 2.0 into V_str.
        let score = score_candidate(&model, &[lsp_import_residual()]).unwrap();
        assert_eq!(score.total, 2.0);
        assert_eq!(score.components.v_str, 2.0);
    }
}