ccd-cli 1.0.0-alpha.2

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
use std::path::Path;

use anyhow::{bail, Result};
use serde::Serialize;

use crate::content_trust::ContentTrust;
use crate::paths::state::StateLayout;

use super::{backlog_state::BacklogRef, Extension, StartupContext};

// --- Assignment ownership ---

#[derive(Clone, Debug)]
pub(crate) enum AssignmentOwner<'a> {
    Session {
        #[allow(dead_code)] // written by kernel, read by extension impls
        session_id: &'a str,
        #[allow(dead_code)] // written by kernel, read by extension impls
        worktree: &'a str,
        #[allow(dead_code)] // written by kernel, read by extension impls
        branch: Option<&'a str>,
    },
    PreSessionBranch {
        #[allow(dead_code)] // written by kernel, read by extension impls
        worktree: &'a str,
        #[allow(dead_code)] // written by kernel, read by extension impls
        branch: &'a str,
    },
}

/// Returned by `ensure_assignment` and `load_session_assignment` —
/// mirrors the owner variant so the caller knows whether the claim
/// is session-keyed or pre-session.
#[cfg_attr(not(feature = "extension-backlog"), allow(dead_code))]
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case", tag = "kind")]
pub(crate) enum AssignmentOwnerView {
    Session { session_id: String },
    PreSessionBranch { branch: String },
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub(crate) struct AssignmentView {
    pub backlog_ref: BacklogRef,
    pub ccd_id: u64,
    pub github_issue_number: u64,
    pub content_trust: ContentTrust,
    pub title: String,
    pub owner: AssignmentOwnerView,
    pub branch: Option<String>,
    pub worktree: String,
}

#[cfg_attr(not(feature = "extension-backlog"), allow(dead_code))]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum AssignmentStatus {
    Existing,
    Assigned,
    Skipped,
}

#[derive(Clone, Debug, Serialize)]
pub(crate) struct AssignmentOutcome {
    pub status: AssignmentStatus,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_step: Option<ExtensionNextStepView>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub assignment: Option<AssignmentView>,
}

// --- Next-step observations (read-only preview) ---

#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub(crate) struct NextStepItem {
    pub backlog_ref: BacklogRef,
    pub ccd_id: u64,
    pub github_issue_number: u64,
    pub content_trust: ContentTrust,
    pub title: String,
    pub branch: Option<String>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum NextStepStatus {
    Observed,
    NeedsInput,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum NextStepConfidence {
    #[allow(dead_code)] // reserved for verified-adapter path
    Verified,
    Cached,
    Unverified,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum NextStepSource {
    ActiveAssignment,
    BacklogAdapter,
    ExplicitActorInput,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub(crate) struct NextStepObservation {
    pub item: NextStepItem,
    pub confidence: NextStepConfidence,
}

/// Full extension-owned next-step view for startup reports. Carries the
/// positive path (observation + confidence) and the negative path
/// (needs_input + source + reason) without teaching the kernel to
/// present extension workflow state as canonical next-step truth.
#[derive(Clone, Debug, Serialize)]
pub(crate) struct ExtensionNextStepView {
    pub status: NextStepStatus,
    pub source: NextStepSource,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub observation: Option<NextStepObservation>,
}

// --- Session boundary ---

pub(crate) struct PodContext<'a> {
    #[allow(dead_code)] // written by kernel, read by extension impls
    pub name: &'a str,
    #[allow(dead_code)] // written by kernel, read by extension impls
    pub shared_root: &'a Path,
}

pub(crate) struct SessionBoundaryContext<'a> {
    #[allow(dead_code)] // written by kernel, read by extension impls
    pub layout: &'a StateLayout,
    #[allow(dead_code)] // written by kernel, read by extension impls
    pub repo_root: &'a Path,
    #[allow(dead_code)] // written by kernel, read by extension impls
    pub locality_id: &'a str,
    #[allow(dead_code)] // written by kernel, read by extension impls
    pub session_id: &'a str,
    #[allow(dead_code)] // written by kernel, read by extension impls
    pub pod: Option<PodContext<'a>>,
}

#[derive(Clone, Debug, Default)]
pub(crate) struct SessionBoundaryEffect {
    #[allow(dead_code)]
    pub adopted: Vec<AssignmentView>,
    #[allow(dead_code)]
    pub pruned: Vec<AssignmentView>,
}

impl SessionBoundaryEffect {
    pub fn empty() -> Self {
        Self::default()
    }
}

// --- Extension-pushed startup alerts ---

#[derive(Clone, Debug, Serialize)]
pub(crate) struct StartupAlert {
    pub check: &'static str,
    pub severity: StartupAlertSeverity,
    pub message: String,
}

#[cfg_attr(not(feature = "extension-backlog"), allow(dead_code))]
#[derive(Clone, Copy, Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum StartupAlertSeverity {
    Warning,
    #[allow(dead_code)]
    Error,
}

// --- Extension-owned startup payload ---

#[derive(Clone, Debug, Serialize)]
pub(crate) struct ExtensionStartupPayload {
    /// Full extension-owned next-step view for startup consumers.
    pub next_step: ExtensionNextStepView,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub assignment: Option<AssignmentOutcome>,
}

// --- Dispatch-owner routing ---

/// Returns the single active dispatch-owning extension, or `None` when
/// no workflow extension is registered.
///
/// **Fail-closed:** if more than one registered extension claims
/// dispatch ownership, this returns an error rather than silently
/// picking by registration order.
pub(crate) fn active_dispatch_owner() -> Result<Option<&'static dyn Extension>> {
    let owners: Vec<_> = super::registered()
        .into_iter()
        .filter(|ext| ext.owns_dispatch())
        .collect();
    match owners.len() {
        0 => Ok(None),
        1 => Ok(Some(owners[0])),
        n => bail!(
            "multiple extensions ({n}) claim dispatch ownership; \
             exactly one is required — check extension registrations"
        ),
    }
}

pub(crate) fn load_session_assignment(
    ctx: &StartupContext<'_>,
    session_id: &str,
) -> Result<Option<AssignmentView>> {
    match active_dispatch_owner()? {
        Some(ext) => ext.load_session_assignment(ctx, session_id),
        None => Ok(None),
    }
}

pub(crate) fn load_branch_assignment(
    ctx: &StartupContext<'_>,
    branch: &str,
) -> Result<Option<AssignmentView>> {
    match active_dispatch_owner()? {
        Some(ext) => ext.load_branch_assignment(ctx, branch),
        None => Ok(None),
    }
}

pub(crate) fn ensure_assignment(
    ctx: &StartupContext<'_>,
    owner: AssignmentOwner<'_>,
) -> Result<AssignmentOutcome> {
    match active_dispatch_owner()? {
        Some(ext) => ext.ensure_assignment(ctx, owner),
        None => Ok(AssignmentOutcome {
            status: AssignmentStatus::Skipped,
            reason: None,
            next_step: None,
            assignment: None,
        }),
    }
}

pub(crate) fn observe_next_step(ctx: &StartupContext<'_>) -> Result<Option<NextStepObservation>> {
    match active_dispatch_owner()? {
        Some(ext) => ext.observe_next_step(ctx),
        None => Ok(None),
    }
}

pub(crate) fn on_session_started(
    ctx: &SessionBoundaryContext<'_>,
) -> Result<SessionBoundaryEffect> {
    match active_dispatch_owner()? {
        Some(ext) => ext.on_session_started(ctx),
        None => Ok(SessionBoundaryEffect::empty()),
    }
}

pub(crate) fn on_session_cleared(
    ctx: &SessionBoundaryContext<'_>,
) -> Result<SessionBoundaryEffect> {
    match active_dispatch_owner()? {
        Some(ext) => ext.on_session_cleared(ctx),
        None => Ok(SessionBoundaryEffect::empty()),
    }
}

pub(crate) fn resolve_assignment_references(
    ctx: &StartupContext<'_>,
    assignment: &AssignmentView,
    cache: Option<&super::backlog_state::GitHubBacklogCache>,
) -> Result<Vec<StartupAlert>> {
    match active_dispatch_owner()? {
        Some(ext) => ext.resolve_assignment_references(ctx, assignment, cache),
        None => Ok(Vec::new()),
    }
}

/// Builds the extension-owned startup payload for the start report.
/// The kernel embeds this as an opaque field rather than deriving
/// next-step guidance as kernel logic.
pub(crate) fn build_startup_payload(
    ctx: &StartupContext<'_>,
    assignment_outcome: &AssignmentOutcome,
) -> Result<ExtensionStartupPayload> {
    let has_dispatch_owner = active_dispatch_owner()?.is_some();
    let next_step = match &assignment_outcome.assignment {
        Some(assignment) => {
            let source = match assignment_outcome.status {
                AssignmentStatus::Assigned => NextStepSource::BacklogAdapter,
                _ => NextStepSource::ActiveAssignment,
            };
            // Derive the observed next step directly from the assignment
            // rather than calling observe_next_step(), which reads the
            // extension-owned dispatch store independently and can drift in
            // multi-claim/shared-pod cases.
            let observation = Some(NextStepObservation {
                item: NextStepItem {
                    backlog_ref: assignment.backlog_ref.clone(),
                    ccd_id: assignment.ccd_id,
                    github_issue_number: assignment.github_issue_number,
                    content_trust: assignment.content_trust,
                    title: assignment.title.clone(),
                    branch: assignment.branch.clone(),
                },
                confidence: if ctx.allow_cached_work {
                    NextStepConfidence::Cached
                } else {
                    NextStepConfidence::Unverified
                },
            });
            ExtensionNextStepView {
                status: NextStepStatus::Observed,
                source,
                reason: None,
                observation,
            }
        }
        None => {
            if let Some(next_step) = assignment_outcome.next_step.clone() {
                next_step
            } else {
                match observe_next_step(ctx)? {
                    Some(observation) => ExtensionNextStepView {
                        status: NextStepStatus::Observed,
                        source: NextStepSource::ActiveAssignment,
                        reason: None,
                        observation: Some(observation),
                    },
                    None => ExtensionNextStepView {
                        status: NextStepStatus::NeedsInput,
                        source: if has_dispatch_owner && assignment_outcome.reason.is_some() {
                            NextStepSource::BacklogAdapter
                        } else {
                            NextStepSource::ExplicitActorInput
                        },
                        reason: assignment_outcome.reason.clone().or_else(|| {
                            Some(
                                "no extension-owned next-step observation is available; \
                                 choose the next item explicitly or use a neutral session name"
                                    .to_owned(),
                            )
                        }),
                        observation: None,
                    },
                }
            }
        }
    };

    Ok(ExtensionStartupPayload {
        next_step,
        assignment: Some(assignment_outcome.clone()),
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn active_dispatch_owner_returns_backlog_when_enabled() {
        let owner = active_dispatch_owner().unwrap();
        #[cfg(feature = "extension-backlog")]
        assert!(owner.is_some());
        #[cfg(not(feature = "extension-backlog"))]
        assert!(owner.is_none());
    }

    #[test]
    fn no_dispatch_owner_returns_skipped_assignment() {
        let outcome = AssignmentOutcome {
            status: AssignmentStatus::Skipped,
            reason: None,
            next_step: None,
            assignment: None,
        };
        assert_eq!(outcome.status, AssignmentStatus::Skipped);
        assert!(outcome.assignment.is_none());
    }

    #[test]
    fn assignment_owner_view_serializes_with_kind_tag() {
        let session = AssignmentOwnerView::Session {
            session_id: "ses_01".to_owned(),
        };
        let json = serde_json::to_string(&session).unwrap();
        assert!(json.contains("\"kind\":\"session\""));

        let pre = AssignmentOwnerView::PreSessionBranch {
            branch: "main".to_owned(),
        };
        let json = serde_json::to_string(&pre).unwrap();
        assert!(json.contains("\"kind\":\"pre_session_branch\""));
    }
}