forge-pilot 0.1.0

Closed-loop orchestrator over runtime advisories, kernel oracles, and canonical Forge export/import lanes
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
//! Act phase of the OODA loop.
//!
//! Executes the selected verification plan (oracle evaluation or
//! paired-patch experiment) and produces an evidence bundle for the
//! canonical Forge export path.

use crate::bundle_builder::{
    build_bundle_from_oracle, build_bundle_from_patch, OracleBundleInput, PatchBundleInput,
};
use crate::config::LoopConfig;
use crate::error::PilotError;
use crate::observe::Observation;
use forge_engine::lab::evidence::{
    RefutationArtifact, RefutationArtifactOutcome, RefutationArtifactType,
};
use forge_engine::{
    select_backend, CargoAdapter, ExperimentConfig, ExperimentEvidenceBundle,
    PairedExperimentRunner, ProjectAdapter, StructuredPatch,
};
use kernel_oracles::{
    evaluate_causal_refuter, evaluate_conservative, evaluate_delta_parity, evaluate_exact_bounded,
    evaluate_minimal_perturbation, evaluate_temporal_replay, DeltaParityAssessment,
    OracleAssessment, OracleRefutationOutcome, OracleRefutationResult, TemporalReplayAssessment,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use stack_ids::{ClaimVersionId, OracleSliceId};
use std::path::Path;
use verification_policy::ExecutionPermit;

/// An advisory-only plan that produces no promotable evidence.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AdvisoryPlan {
    pub description: String,
}

/// The concrete execution plan selected for a verification target.
///
/// Each variant determines which kernel oracle or paired-patch path
/// will be used during the act phase.
#[derive(Debug, Clone)]
pub enum PlanKind {
    OracleExactBounded {
        oracle_slice_id: OracleSliceId,
    },
    OracleConservative,
    OracleDeltaParity {
        changed_node_ids: Vec<String>,
        max_iterations: u32,
    },
    OracleTemporalReplay {
        cutoff_recorded_at: String,
    },
    OracleCausalRefuter {
        target_node_id: String,
        max_removed_nodes: usize,
    },
    OracleMinimalPerturbation {
        target_node_id: String,
        max_removed_nodes: usize,
    },
    PairedPatch {
        fixture_path: String,
        patch: StructuredPatch,
        experiment_config: ExperimentConfig,
        description: String,
    },
    AdvisoryOnlyVerificationPlan(AdvisoryPlan),
}

impl PlanKind {
    /// Returns the superseded claim version targeted by this plan, if any.
    pub fn supersedes_claim_version_id(&self) -> Option<ClaimVersionId> {
        None
    }

    /// Returns the verification check names implied by this plan.
    pub fn check_names(&self) -> Vec<String> {
        match self {
            Self::PairedPatch { .. } => vec!["fmt".into(), "clippy".into(), "test".into()],
            _ => vec!["kernel_oracle".into()],
        }
    }
}

/// Broad classification of the action executed during the act phase.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ActionFamily {
    Oracle,
    PairedPatch,
    AdvisoryOnly,
}

/// Results from running kernel oracle evaluation against compiled constraints.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OracleExecution {
    pub assessment: Option<OracleAssessment>,
    pub delta_parity: Option<DeltaParityAssessment>,
    pub temporal_replay: Option<TemporalReplayAssessment>,
    pub refutation: Option<OracleRefutationResult>,
}

impl OracleExecution {
    /// Returns a short textual summary of the oracle execution outcome.
    pub fn outcome_summary(&self) -> Option<String> {
        if let Some(assessment) = &self.assessment {
            return Some(format!(
                "oracle mode {:?} supported={} satisfied_constraints={}",
                assessment.mode, assessment.supported, assessment.satisfied_constraint_count
            ));
        }
        if let Some(delta) = &self.delta_parity {
            return Some(format!(
                "delta parity matched={} recomputed_nodes={}",
                delta.parity_match,
                delta.recomputed_node_ids.len()
            ));
        }
        if let Some(replay) = &self.temporal_replay {
            return Some(format!(
                "temporal replay matched_expected_hash={}",
                replay.matched_expected_hash
            ));
        }
        self.refutation
            .as_ref()
            .map(|refutation| format!("{:?}", refutation.outcome))
    }

    /// Returns a JSON summary of the oracle execution outcome.
    pub fn summary_json(&self) -> serde_json::Value {
        serde_json::json!({
            "assessment": self.assessment,
            "delta_parity": self.delta_parity,
            "temporal_replay": self.temporal_replay,
            "refutation": self.refutation,
        })
    }

    /// Returns the refutation artifacts emitted by this oracle execution.
    pub fn refutation_artifacts(&self) -> Vec<RefutationArtifact> {
        self.refutation
            .iter()
            .map(|refutation| RefutationArtifact {
                artifact_id: format!("refutation:{}", refutation.target_node_id),
                artifact_type: RefutationArtifactType::SubsampleStability,
                trial_id: None,
                attempt_id: None,
                outcome: match &refutation.outcome {
                    OracleRefutationOutcome::FlipWitness { .. } => {
                        RefutationArtifactOutcome::Passed
                    }
                    OracleRefutationOutcome::NoFlipFound { searched_budget } => {
                        RefutationArtifactOutcome::Failed {
                            reason: format!("no flip found in budget {searched_budget}"),
                        }
                    }
                    OracleRefutationOutcome::NotApplicable { reason } => {
                        RefutationArtifactOutcome::Inconclusive {
                            reason: reason.clone(),
                        }
                    }
                },
                estimate_delta: None,
                details: Some(format!("{:?}", refutation.outcome)),
            })
            .collect()
    }
}

/// Results from running a paired-patch experiment through the Forge engine.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PatchExecution {
    pub run_id: String,
    pub improvements: u32,
    pub regressions: u32,
}

/// Full outcome of executing a plan, including the evidence bundle and execution details.
#[derive(Debug, Clone)]
pub struct ActionOutcome {
    pub family: ActionFamily,
    pub plan: PlanKind,
    pub bundle: Option<ExperimentEvidenceBundle>,
    pub oracle_execution: Option<OracleExecution>,
    pub patch_execution: Option<PatchExecution>,
    pub advisory_only: bool,
    pub outcome_signature: String,
}

/// Executes a verification plan under an issued execution permit.
///
/// Dispatches to the appropriate oracle or paired-patch path based on
/// the plan variant. Returns an error if the permit scope does not
/// match `target_key`.
pub async fn execute_plan(
    observation: &Observation,
    target_key: &str,
    plan: &PlanKind,
    permit: &ExecutionPermit,
    config: &LoopConfig,
) -> Result<ActionOutcome, PilotError> {
    if permit.scope().target_key() != target_key {
        return Err(PilotError::Other(format!(
            "execution permit target {} does not match requested target {}",
            permit.scope().target_key(),
            target_key
        )));
    }
    match plan {
        PlanKind::OracleExactBounded { .. }
        | PlanKind::OracleConservative
        | PlanKind::OracleDeltaParity { .. }
        | PlanKind::OracleTemporalReplay { .. }
        | PlanKind::OracleCausalRefuter { .. }
        | PlanKind::OracleMinimalPerturbation { .. } => {
            execute_oracle_plan(observation, target_key, plan, config).await
        }
        PlanKind::PairedPatch {
            fixture_path,
            patch,
            experiment_config,
            ..
        } => {
            execute_patch_plan(
                observation,
                target_key,
                plan,
                fixture_path,
                patch,
                experiment_config,
                config,
            )
            .await
        }
        PlanKind::AdvisoryOnlyVerificationPlan(_) => Err(PilotError::Other(
            "advisory-only plans cannot consume execution permits".into(),
        )),
    }
}

async fn execute_oracle_plan(
    observation: &Observation,
    target_key: &str,
    plan: &PlanKind,
    _config: &LoopConfig,
) -> Result<ActionOutcome, PilotError> {
    let compiled = observation
        .compiled
        .as_ref()
        .ok_or(PilotError::MissingCompiledContext)?;

    let oracle_execution = match plan {
        PlanKind::OracleExactBounded { .. } => OracleExecution {
            assessment: evaluate_exact_bounded(compiled),
            delta_parity: None,
            temporal_replay: None,
            refutation: None,
        },
        PlanKind::OracleConservative => OracleExecution {
            assessment: Some(evaluate_conservative(compiled)),
            delta_parity: None,
            temporal_replay: None,
            refutation: None,
        },
        PlanKind::OracleDeltaParity {
            changed_node_ids,
            max_iterations,
        } => OracleExecution {
            assessment: None,
            delta_parity: Some(evaluate_delta_parity(
                compiled,
                changed_node_ids,
                *max_iterations,
            )),
            temporal_replay: None,
            refutation: None,
        },
        PlanKind::OracleTemporalReplay { cutoff_recorded_at } => OracleExecution {
            assessment: None,
            delta_parity: None,
            temporal_replay: Some(
                evaluate_temporal_replay(
                    &observation.temporal_snapshots,
                    cutoff_recorded_at,
                    &constraint_compiler::CompilerPolicy {
                        policy_version: "forge-pilot.v1".into(),
                        include_hyperedges: true,
                    },
                    &compiled.graph_hash,
                )
                .ok_or(PilotError::MissingTemporalSnapshots)?,
            ),
            refutation: None,
        },
        PlanKind::OracleCausalRefuter {
            target_node_id,
            max_removed_nodes,
        } => OracleExecution {
            assessment: None,
            delta_parity: None,
            temporal_replay: None,
            refutation: Some(evaluate_causal_refuter(
                compiled,
                target_node_id,
                *max_removed_nodes,
            )),
        },
        PlanKind::OracleMinimalPerturbation {
            target_node_id,
            max_removed_nodes,
        } => OracleExecution {
            assessment: None,
            delta_parity: None,
            temporal_replay: None,
            refutation: Some(evaluate_minimal_perturbation(
                compiled,
                target_node_id,
                *max_removed_nodes,
            )),
        },
        // LIB-HIGH-001: replaced unreachable!() with recoverable error
        _ => {
            return Err(PilotError::Other(format!(
                "unsupported plan kind for oracle execution: {:?}",
                plan
            )))
        }
    };

    let bundle = build_bundle_from_oracle(OracleBundleInput {
        plan,
        target_key,
        trace_id: observation
            .batch
            .as_ref()
            .and_then(|batch| batch.trace_ctx.as_ref().map(|ctx| ctx.trace_id.clone())),
        scope_namespace: &observation.scope_key.namespace,
        oracle_execution: &oracle_execution,
        known_threats: observation
            .degradations
            .iter()
            .map(|degradation| degradation.kind.clone())
            .collect(),
    });
    let outcome_signature = oracle_execution
        .outcome_summary()
        .unwrap_or_else(|| "oracle".into());

    Ok(ActionOutcome {
        family: ActionFamily::Oracle,
        plan: plan.clone(),
        bundle: Some(bundle),
        oracle_execution: Some(oracle_execution),
        patch_execution: None,
        advisory_only: false,
        outcome_signature,
    })
}

async fn execute_patch_plan(
    observation: &Observation,
    target_key: &str,
    plan: &PlanKind,
    fixture_path: &str,
    patch: &StructuredPatch,
    experiment_config: &ExperimentConfig,
    config: &LoopConfig,
) -> Result<ActionOutcome, PilotError> {
    let backend = select_backend(&config.forge_config)?;
    let fixture = Path::new(fixture_path);
    if !CargoAdapter::detect(fixture) {
        return Err(PilotError::UnsupportedPatchFixture {
            fixture_path: fixture_path.to_string(),
        });
    }
    let adapter = CargoAdapter;
    let runner = PairedExperimentRunner::new(backend.as_ref(), &adapter, &config.forge_config);
    let experiment_result = runner.run(fixture, patch, experiment_config).await?;
    let bundle = build_bundle_from_patch(PatchBundleInput {
        plan,
        target_key,
        trace_id: observation
            .batch
            .as_ref()
            .and_then(|batch| batch.trace_ctx.as_ref().map(|ctx| ctx.trace_id.clone())),
        scope_namespace: &observation.scope_key.namespace,
        experiment_result: &experiment_result,
        known_threats: observation
            .degradations
            .iter()
            .map(|degradation| degradation.kind.clone())
            .collect(),
    });

    Ok(ActionOutcome {
        family: ActionFamily::PairedPatch,
        plan: plan.clone(),
        bundle: Some(bundle),
        oracle_execution: None,
        patch_execution: Some(PatchExecution {
            run_id: experiment_result.run_id.clone(),
            improvements: experiment_result.diff.improvements,
            regressions: experiment_result.diff.regressions,
        }),
        advisory_only: false,
        outcome_signature: format!(
            "patch:improvements={} regressions={}",
            experiment_result.diff.improvements, experiment_result.diff.regressions
        ),
    })
}