ccd-cli 1.0.0-beta.5

Bootstrap and validate Continuous Context Development repositories
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
use crate::handoff;
use crate::session_boundary::SessionBoundaryAction;
use crate::state::escalation as escalation_state;
use crate::state::runtime as runtime_state;
use crate::state::session as session_state;
use crate::state::session_gates;

use super::{
    BehavioralDriftState, CandidateUpdate, CheckpointResult, ContextCheckAction,
    ContextCheckPayload, ContextCheckTrigger, ContextCheckUrgency, ContextHealth,
    DriftAggregateStatus, HandoffState, NextStepStatus, RadarSessionStateView, RadarStateReport,
};

pub(super) struct ContextCheckDecision {
    pub(super) action: ContextCheckAction,
    pub(super) reason: &'static str,
    pub(super) recommendation: String,
    pub(super) urgency: ContextCheckUrgency,
    pub(super) suppressed: bool,
    pub(super) next_interval_hint_seconds: u64,
    pub(super) evidence: Vec<String>,
}

/// Lightweight input struct for the context-check decision tree — can be
/// populated from either a full `RadarStateReport` (handover path) or a
/// `CheckpointResult` (lightweight path for low-value triggers like
/// interval/supervisor-poll). This decouples the decision tree from the
/// expensive `evaluate()` codepath (#627).
pub(super) struct ContextCheckInputs<'a> {
    pub(super) checkout_state: Option<&'a handoff::CheckoutStateView>,
    pub(super) escalation: &'a escalation_state::EscalationView,
    pub(super) behavioral_drift: &'a BehavioralDriftState,
    pub(super) context_health: &'a ContextHealth,
    pub(super) session_boundary_action: SessionBoundaryAction,
    pub(super) session_boundary_evidence: &'a [String],
    pub(super) next_step_status: NextStepStatus,
    pub(super) next_step_summary: String,
    pub(super) next_step_evidence: Vec<String>,
    pub(super) execution_gates: &'a session_gates::ExecutionGatesView,
    pub(super) recovery_status: &'a str,
    pub(super) handoff: &'a HandoffState,
    pub(super) candidate_updates_handoff: &'a [CandidateUpdate],
    pub(super) candidate_updates_memory_count: usize,
    pub(super) session_state: &'a RadarSessionStateView,
}

impl<'a> ContextCheckInputs<'a> {
    /// Build inputs from a full handover RadarStateReport.
    pub(super) fn from_handover(report: &'a RadarStateReport) -> Self {
        Self {
            checkout_state: report.checkout_state.as_ref(),
            escalation: &report.escalation,
            behavioral_drift: &report.behavioral_drift,
            context_health: &report.context_health,
            session_boundary_action: report.session_boundary.action,
            session_boundary_evidence: &report.session_boundary.evidence,
            next_step_status: report.evaluation.next_step.status,
            next_step_summary: report.evaluation.next_step.summary.clone(),
            next_step_evidence: report.evaluation.next_step.evidence.clone(),
            execution_gates: &report.execution_gates,
            recovery_status: report.recovery.status,
            handoff: &report.handoff,
            candidate_updates_handoff: &report.candidate_updates.handoff,
            candidate_updates_memory_count: report.candidate_updates.memory.len(),
            session_state: &report.session_state,
        }
    }

    /// Build inputs from a lightweight checkpoint — avoids the expensive
    /// `evaluate()` path. Computes `next_step_status` directly from the
    /// handoff candidates and execution gates already present in the
    /// checkpoint result (#627).
    pub(super) fn from_checkpoint(cp: &'a CheckpointResult) -> Self {
        // Replicate the next_step logic from evaluation::build_next_step_bucket
        // without requiring the full evaluation pipeline.
        let (next_step_status, next_step_summary, next_step_evidence) = if !cp
            .candidate_updates
            .handoff
            .is_empty()
        {
            (
                    NextStepStatus::ReviewRequired,
                    "Repo state changed relative to the recorded handoff; refresh the workspace-local handoff before closing.".to_owned(),
                    cp.candidate_updates
                        .handoff
                        .iter()
                        .map(|c| c.summary.clone())
                        .collect(),
                )
        } else if cp
            .execution_gates
            .attention_anchor
            .as_ref()
            .is_some_and(|a| a.status == session_gates::ExecutionGateStatus::Blocked)
        {
            (
                NextStepStatus::ReviewRequired,
                "The first unfinished execution gate is blocked.".to_owned(),
                Vec::new(),
            )
        } else if cp.execution_gates.attention_anchor.is_some() {
            (
                NextStepStatus::Continue,
                "Execution gates are active.".to_owned(),
                Vec::new(),
            )
        } else {
            (
                NextStepStatus::NoChangeDetected,
                "No deterministic CLI signal says the next step changed.".to_owned(),
                Vec::new(),
            )
        };

        Self {
            checkout_state: cp.checkout_state.as_ref(),
            escalation: &cp.escalation,
            behavioral_drift: &cp.behavioral_drift,
            context_health: &cp.context_health,
            session_boundary_action: cp.session_boundary.inner.action,
            session_boundary_evidence: &cp.session_boundary.inner.evidence,
            next_step_status,
            next_step_summary,
            next_step_evidence,
            execution_gates: &cp.execution_gates,
            recovery_status: cp.recovery.status,
            handoff: &cp.handoff,
            candidate_updates_handoff: &cp.candidate_updates.handoff,
            // Memory candidates are not computed in checkpoint-only path.
            candidate_updates_memory_count: 0,
            session_state: &cp.session_state,
        }
    }
}

pub(super) fn decide(
    trigger: ContextCheckTrigger,
    inputs: &ContextCheckInputs<'_>,
    payload: &ContextCheckPayload,
) -> ContextCheckDecision {
    if let Some(checkout_state) = inputs.checkout_state.filter(|state| state.advisory) {
        return ContextCheckDecision {
            action: ContextCheckAction::Escalate,
            reason: "checkout_advisory",
            recommendation: "seek_operator_attention".to_owned(),
            urgency: ContextCheckUrgency::High,
            suppressed: false,
            next_interval_hint_seconds: 0,
            evidence: vec![checkout_state.summary.clone()],
        };
    }

    if inputs.escalation.blocking_count > 0 {
        return ContextCheckDecision {
            action: ContextCheckAction::Escalate,
            reason: "blocking_escalation",
            recommendation: "seek_operator_attention".to_owned(),
            urgency: ContextCheckUrgency::Critical,
            suppressed: false,
            next_interval_hint_seconds: 0,
            evidence: inputs
                .escalation
                .entries
                .iter()
                .filter(|entry| matches!(entry.kind, escalation_state::EscalationKind::Blocking))
                .map(|entry| format!("{}: {}", entry.id, entry.reason))
                .collect(),
        };
    }

    if inputs.behavioral_drift.status == DriftAggregateStatus::NeedsRecalibration {
        return ContextCheckDecision {
            action: ContextCheckAction::Escalate,
            reason: "behavioral_drift",
            recommendation: "recalibrate_session".to_owned(),
            urgency: ContextCheckUrgency::High,
            suppressed: false,
            next_interval_hint_seconds: 0,
            evidence: inputs.behavioral_drift.evidence.clone(),
        };
    }

    if matches!(
        trigger,
        ContextCheckTrigger::PreCompaction | ContextCheckTrigger::IdleReset
    ) {
        let reason = match trigger {
            ContextCheckTrigger::PreCompaction => "pre_compaction",
            ContextCheckTrigger::IdleReset => "idle_reset",
            _ => unreachable!("guarded above"),
        };
        let mut evidence = vec![payload.risk_summary.clone()];
        evidence.extend(inputs.session_boundary_evidence.iter().take(2).cloned());
        return ContextCheckDecision {
            action: ContextCheckAction::FlushForCompaction,
            reason,
            recommendation: "capture_before_compaction".to_owned(),
            urgency: ContextCheckUrgency::High,
            suppressed: false,
            next_interval_hint_seconds: 0,
            evidence,
        };
    }

    if matches!(
        inputs.context_health.recommendation,
        "wrap_up_soon" | "wrap_up_and_clear"
    ) {
        return ContextCheckDecision {
            action: ContextCheckAction::WrapUpRequired,
            reason: "wrap_up_window",
            recommendation: inputs.context_health.recommendation.to_owned(),
            urgency: match inputs.context_health.recommendation {
                "wrap_up_and_clear" => ContextCheckUrgency::Critical,
                _ => ContextCheckUrgency::High,
            },
            suppressed: false,
            next_interval_hint_seconds: 0,
            evidence: if inputs.session_boundary_evidence.is_empty() {
                vec![payload.risk_summary.clone()]
            } else {
                inputs.session_boundary_evidence.to_vec()
            },
        };
    }

    if inputs.session_boundary_action == SessionBoundaryAction::Refresh
        || inputs.next_step_status == NextStepStatus::ReviewRequired
    {
        return ContextCheckDecision {
            action: ContextCheckAction::CheckpointNow,
            reason: "handoff_refresh_needed",
            recommendation: "checkpoint_now".to_owned(),
            urgency: ContextCheckUrgency::Moderate,
            suppressed: false,
            next_interval_hint_seconds: 0,
            evidence: if inputs.next_step_evidence.is_empty() {
                vec![payload.state_delta.clone()]
            } else {
                inputs.next_step_evidence.clone()
            },
        };
    }

    let manualish_trigger = matches!(
        trigger,
        ContextCheckTrigger::Manual
            | ContextCheckTrigger::Resume
            | ContextCheckTrigger::SupervisorPoll
    );
    let moderate_pressure = matches!(inputs.context_health.band, "moderate" | "risky")
        || inputs.execution_gates.unfinished_count > 0
        || inputs.recovery_status == "loaded";
    if manualish_trigger || moderate_pressure {
        return ContextCheckDecision {
            action: ContextCheckAction::InjectDelta,
            reason: match trigger {
                ContextCheckTrigger::Resume => "resume_refresh",
                ContextCheckTrigger::SupervisorPoll => "supervisor_poll",
                ContextCheckTrigger::Manual => "manual_refresh",
                _ => "band_transition",
            },
            recommendation: match trigger {
                ContextCheckTrigger::Resume => "resume_with_digest".to_owned(),
                _ => inputs.context_health.recommendation.to_owned(),
            },
            urgency: if matches!(inputs.context_health.band, "risky") {
                ContextCheckUrgency::High
            } else {
                ContextCheckUrgency::Moderate
            },
            suppressed: false,
            next_interval_hint_seconds: if matches!(trigger, ContextCheckTrigger::Resume) {
                300
            } else {
                600
            },
            evidence: vec![payload.state_delta.clone(), payload.risk_summary.clone()],
        };
    }

    ContextCheckDecision {
        action: ContextCheckAction::None,
        reason: if trigger == ContextCheckTrigger::Interval {
            "interval_suppressed"
        } else {
            "no_action"
        },
        recommendation: "continue".to_owned(),
        urgency: ContextCheckUrgency::Low,
        suppressed: trigger == ContextCheckTrigger::Interval,
        next_interval_hint_seconds: 900,
        evidence: vec![payload.risk_summary.clone()],
    }
}

/// Backward-compatible wrapper: delegates to `decide()` via
/// `ContextCheckInputs::from_handover`. Retained for reference paths
/// that name the function.
#[allow(dead_code)]
pub(super) fn build_context_check_decision(
    trigger: ContextCheckTrigger,
    report: &RadarStateReport,
    payload: &ContextCheckPayload,
) -> ContextCheckDecision {
    let inputs = ContextCheckInputs::from_handover(report);
    decide(trigger, &inputs, payload)
}

pub(super) fn build_policy_digest(runtime: &runtime_state::LoadedRuntimeState) -> String {
    let guardrails: Vec<String> = runtime
        .state
        .handoff
        .operational_guardrails
        .iter()
        .map(|item| item.text.clone())
        .collect();
    if guardrails.is_empty() {
        return "No compiled operational guardrails are currently recorded.".to_owned();
    }

    summarize_lines(&guardrails, 2)
}

pub(super) fn build_focus_digest_from_inputs(inputs: &ContextCheckInputs<'_>) -> String {
    let mut parts = vec![inputs.handoff.title.clone()];
    if let Some(mode) = inputs
        .session_state
        .mode
        .filter(|mode| *mode != session_state::SessionMode::General)
    {
        parts.push(format!("mode `{}`", mode.as_str()));
    }
    if let Some(anchor) = &inputs.execution_gates.attention_anchor {
        parts.push(format!(
            "gate [{} #{}/{}] {}",
            anchor.status.as_str(),
            anchor.index,
            inputs.execution_gates.total_count,
            anchor.text
        ));
    } else if let Some(next_action) = inputs.handoff.immediate_actions.first() {
        parts.push(format!("next `{next_action}`"));
    }

    parts.join("; ")
}

/// Backward-compatible wrapper for full handover reports.
#[allow(dead_code)]
pub(super) fn build_focus_digest(report: &RadarStateReport) -> String {
    let inputs = ContextCheckInputs::from_handover(report);
    build_focus_digest_from_inputs(&inputs)
}

pub(super) fn build_state_delta_from_inputs(inputs: &ContextCheckInputs<'_>) -> String {
    let mut parts = Vec::new();
    if !inputs.candidate_updates_handoff.is_empty() {
        parts.push(format!(
            "{} handoff update candidate(s)",
            inputs.candidate_updates_handoff.len()
        ));
    }
    if inputs.candidate_updates_memory_count > 0 {
        parts.push(format!(
            "{} memory promotion candidate(s)",
            inputs.candidate_updates_memory_count
        ));
    }
    if let Some(anchor) = &inputs.execution_gates.attention_anchor {
        parts.push(format!(
            "execution gate [{} #{}/{}] {}",
            anchor.status.as_str(),
            anchor.index,
            inputs.execution_gates.total_count,
            anchor.text
        ));
    }
    if parts.is_empty() {
        parts.push(inputs.next_step_summary.clone());
    }
    parts.join("; ")
}

/// Backward-compatible wrapper for full handover reports.
#[allow(dead_code)]
pub(super) fn build_state_delta(report: &RadarStateReport) -> String {
    let inputs = ContextCheckInputs::from_handover(report);
    build_state_delta_from_inputs(&inputs)
}

pub(super) fn build_risk_summary_from_inputs(
    trigger: ContextCheckTrigger,
    inputs: &ContextCheckInputs<'_>,
) -> String {
    let mut parts = vec![format!(
        "trigger `{}` with context band `{}` (`{}`)",
        trigger.as_str(),
        inputs.context_health.band,
        inputs.context_health.recommendation
    )];
    if inputs.behavioral_drift.status == DriftAggregateStatus::NeedsRecalibration {
        parts.push("behavioral drift needs recalibration".to_owned());
    }
    if inputs.escalation.blocking_count > 0 {
        parts.push(format!(
            "{} blocking escalation(s) active",
            inputs.escalation.blocking_count
        ));
    }
    parts.push(format!(
        "session boundary is `{}`",
        inputs.session_boundary_action.as_str()
    ));
    parts.join("; ")
}

/// Backward-compatible wrapper for full handover reports.
#[allow(dead_code)]
pub(super) fn build_risk_summary(
    trigger: ContextCheckTrigger,
    report: &RadarStateReport,
) -> String {
    let inputs = ContextCheckInputs::from_handover(report);
    build_risk_summary_from_inputs(trigger, &inputs)
}

fn summarize_lines(lines: &[String], limit: usize) -> String {
    let mut parts: Vec<String> = lines.iter().take(limit).cloned().collect();
    if lines.len() > limit {
        parts.push(format!("+{} more", lines.len() - limit));
    }
    parts.join("; ")
}