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
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
pub(crate) mod escalation;
pub(crate) mod handoff;
pub(crate) mod memory_ops;
pub(crate) mod migration;
pub(crate) mod projection;
pub(crate) mod recovery;
pub(crate) mod schema;
pub(crate) mod session;
pub(crate) mod session_activity;
pub(crate) mod session_gates;
pub(crate) mod telemetry_cost;

use std::path::{Component, Path};

use anyhow::{Context, Result};
use rusqlite::{Connection, Error as SqliteError, ErrorCode};
use tracing::debug;

use crate::paths::state::StateLayout;

pub(crate) struct StateDb {
    conn: Connection,
}

impl StateDb {
    pub(crate) fn open(path: &Path) -> Result<Self> {
        let needs_init = !path.exists();
        debug!(path = %path.display(), needs_init, "opening state.db");
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("create state.db parent: {}", parent.display()))?;
        }
        let conn = Connection::open(path)
            .map_err(|error| wrap_state_db_open_error(path, needs_init, error))?;
        conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON;")?;
        if needs_init {
            debug!("initializing fresh state.db schema");
            schema::initialize(&conn)?;
        } else {
            debug!("running state.db schema migration check");
            schema::migrate(&conn)?;
        }
        debug!(path = %path.display(), "state.db ready");
        Ok(Self { conn })
    }

    pub(crate) fn open_with_migration(path: &Path, layout: &StateLayout) -> Result<Self> {
        let db = Self::open(path)?;
        // Always check for legacy files — handles both fresh DBs and
        // previously aborted migrations where the DB exists but some
        // legacy files were not yet imported/renamed.
        let report = migration::import_legacy_json(&db, layout)?;
        if report.imported_count > 0 {
            eprintln!(
                "ccd: migrated {} legacy state file(s) to state.db",
                report.imported_count
            );
        }
        Ok(db)
    }

    /// Convenience: resolve path from layout and open with migration.
    pub(crate) fn open_for_layout(layout: &StateLayout) -> Result<Self> {
        Self::open_with_migration(&layout.state_db_path(), layout)
    }

    pub(crate) fn conn(&self) -> &Connection {
        &self.conn
    }
}

fn wrap_state_db_open_error(path: &Path, needs_init: bool, error: SqliteError) -> anyhow::Error {
    let is_cannot_open =
        matches!(&error, SqliteError::SqliteFailure(err, _) if err.code == ErrorCode::CannotOpen);
    let base = anyhow::Error::new(error).context(format!("open state.db: {}", path.display()));
    if needs_init && is_linked_worktree_clone_state_path(path) && is_cannot_open {
        return base.context(format!(
            "first-create failed for workspace-local state under the shared linked-worktree gitdir at {}; some sandboxed environments can read the checkout but cannot create new files under `.git/worktrees/...`. Re-run this command once with broader filesystem access or pre-create `state.db` outside the sandbox",
            path.display()
        ));
    }

    base
}

fn is_linked_worktree_clone_state_path(path: &Path) -> bool {
    let mut saw_dot_git = false;
    for component in path.components() {
        let Component::Normal(segment) = component else {
            continue;
        };

        if !saw_dot_git {
            if segment == ".git" {
                saw_dot_git = true;
            }
            continue;
        }

        return segment == "worktrees";
    }

    false
}

#[cfg(test)]
mod integration_tests {
    use std::fs;

    use tempfile::tempdir;

    use super::*;
    use crate::profile::ProfileName;
    use crate::state::escalation::{EscalationEntry, EscalationKind};
    use crate::state::projection_metadata::ProjectionObservation;
    use crate::state::runtime::{
        RecoveryOrigin, RuntimeCheckpointState, RuntimeHandoffItem, RuntimeHandoffState,
        RuntimeLifecycle, RuntimeWorkingBufferState,
    };
    use crate::state::session::SessionStateFile;

    fn test_layout(temp: &Path) -> StateLayout {
        StateLayout::new(
            temp.join(".ccd"),
            temp.join("repo/.git/ccd"),
            ProfileName::new("main").expect("profile"),
        )
    }

    fn setup_dirs(layout: &StateLayout) {
        fs::create_dir_all(layout.clone_profile_root()).expect("clone profile root");
        fs::create_dir_all(layout.clone_runtime_state_root()).expect("clone runtime root");
    }

    fn interactive_session(
        schema_version: u32,
        started_at_epoch_s: u64,
        last_started_at_epoch_s: u64,
        start_count: u32,
        session_id: Option<&str>,
        mode: crate::state::session::SessionMode,
    ) -> SessionStateFile {
        SessionStateFile {
            schema_version,
            started_at_epoch_s,
            last_started_at_epoch_s,
            start_count,
            session_id: session_id.map(str::to_owned),
            mode,
            owner_kind: crate::state::session::SessionOwnerKind::Interactive,
            owner_id: session_id.map(|_| "interactive".to_owned()),
            supervisor_id: None,
            lease_ttl_secs: None,
            last_heartbeat_at_epoch_s: None,
            revision: u64::from(session_id.is_some()),
        }
    }

    // --- Lifecycle: open, write, read across all tables ---

    #[test]
    fn full_lifecycle_across_all_tables() {
        let temp = tempdir().unwrap();
        let layout = test_layout(temp.path());
        setup_dirs(&layout);

        let db = StateDb::open_for_layout(&layout).unwrap();

        // Session
        let sess = interactive_session(
            3,
            1_000_000,
            1_000_050,
            2,
            Some("ses_LIFECYCLE"),
            crate::state::session::SessionMode::Research,
        );
        session::write(db.conn(), &sess).unwrap();
        let loaded_sess = session::read(db.conn()).unwrap().expect("session");
        assert_eq!(loaded_sess.session_id.as_deref(), Some("ses_LIFECYCLE"));
        assert_eq!(loaded_sess.start_count, 2);
        assert_eq!(
            loaded_sess.mode,
            crate::state::session::SessionMode::Research
        );

        // Handoff
        let ho = RuntimeHandoffState {
            title: "Integration test".to_owned(),
            immediate_actions: vec![RuntimeHandoffItem {
                text: "Run full lifecycle test.".to_owned(),
                lifecycle: RuntimeLifecycle::Active,
            }],
            completed_state: vec![RuntimeHandoffItem {
                text: "Schema created.".to_owned(),
                lifecycle: RuntimeLifecycle::Active,
            }],
            ..RuntimeHandoffState::default()
        };
        handoff::write(db.conn(), &ho).unwrap();
        let loaded_ho = handoff::read(db.conn()).unwrap().expect("handoff");
        assert_eq!(loaded_ho.title, "Integration test");
        assert_eq!(loaded_ho.immediate_actions.len(), 1);
        assert_eq!(loaded_ho.completed_state.len(), 1);

        // Escalation
        let esc = EscalationEntry {
            id: "esc_INT_1".to_owned(),
            kind: EscalationKind::Blocking,
            reason: "integration test".to_owned(),
            created_at_epoch_s: 1_000_000,
            session_id: Some("ses_LIFECYCLE".to_owned()),
        };
        escalation::insert(db.conn(), &esc).unwrap();
        assert!(escalation::has_blocking(db.conn()).unwrap());

        let entries = escalation::list(db.conn()).unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].id, "esc_INT_1");

        // Recovery — checkpoint
        let cp = RuntimeCheckpointState {
            origin: RecoveryOrigin::Compaction,
            captured_at_epoch_s: 1_000_100,
            session_started_at_epoch_s: 1_000_000,
            summary: "Full lifecycle checkpoint".to_owned(),
            immediate_actions: vec!["Next step".to_owned()],
            key_files: vec!["src/db/mod.rs".to_owned()],
        };
        recovery::write_checkpoint(db.conn(), &cp).unwrap();
        let loaded_cp = recovery::read_checkpoint(db.conn())
            .unwrap()
            .expect("checkpoint");
        assert_eq!(loaded_cp.summary, "Full lifecycle checkpoint");

        // Recovery — working buffer
        let buf = RuntimeWorkingBufferState {
            origin: RecoveryOrigin::RiskyPause,
            captured_at_epoch_s: 1_000_200,
            session_started_at_epoch_s: 1_000_000,
            summary_lines: vec!["Line 1".to_owned(), "Line 2".to_owned()],
        };
        recovery::write_working_buffer(db.conn(), &buf).unwrap();
        let loaded_buf = recovery::read_working_buffer(db.conn())
            .unwrap()
            .expect("buffer");
        assert_eq!(loaded_buf.summary_lines.len(), 2);

        // Projection
        let obs = ProjectionObservation {
            observed_at_epoch_s: 1_000_300,
            source_fingerprint: "fp_lifecycle".to_owned(),
            projection_digests: None,
            tool_surface_fingerprint: Some("tool_v1".to_owned()),
            session_id: None,
        };
        projection::record(db.conn(), &obs).unwrap();
        let projections = projection::list(db.conn()).unwrap();
        assert_eq!(projections.len(), 1);
        assert_eq!(projections[0].source_fingerprint, "fp_lifecycle");
    }

    // --- Migration: legacy JSON files imported on first open ---

    #[test]
    fn open_for_layout_migrates_legacy_json() {
        let temp = tempdir().unwrap();
        let layout = test_layout(temp.path());
        setup_dirs(&layout);

        // Write legacy session file
        fs::write(
            layout.session_state_path(),
            r#"{"schema_version":3,"started_at_epoch_s":5000,"last_started_at_epoch_s":6000,"start_count":4,"session_id":"ses_LEGACY"}"#,
        ).unwrap();

        // Write legacy handoff file
        fs::write(
            layout.clone_runtime_state_path(),
            r#"{"schema_version":1,"handoff":{"title":"Legacy handoff","immediate_actions":[{"text":"Migrated action.","lifecycle":"active"}],"completed_state":[],"operational_guardrails":[],"key_files":[],"definition_of_done":[]}}"#,
        ).unwrap();

        // Write legacy escalation file
        fs::write(
            layout.escalation_state_path(),
            r#"{"schema_version":1,"entries":[{"id":"esc_LEGACY","kind":"non_blocking","reason":"legacy escalation","created_at_epoch_s":7000}]}"#,
        ).unwrap();

        let db = StateDb::open_for_layout(&layout).unwrap();

        // Verify migration
        let sess = session::read(db.conn()).unwrap().expect("migrated session");
        assert_eq!(sess.session_id.as_deref(), Some("ses_LEGACY"));
        assert_eq!(sess.start_count, 4);

        let ho = handoff::read(db.conn()).unwrap().expect("migrated handoff");
        assert_eq!(ho.title, "Legacy handoff");
        assert_eq!(ho.immediate_actions.len(), 1);

        let entries = escalation::list(db.conn()).unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].id, "esc_LEGACY");
        assert_eq!(entries[0].kind, EscalationKind::NonBlocking);

        // Legacy files renamed
        assert!(!layout.session_state_path().exists());
        assert!(!layout.clone_runtime_state_path().exists());
        assert!(!layout.escalation_state_path().exists());

        let mut migrated = layout.session_state_path().as_os_str().to_owned();
        migrated.push(".migrated");
        assert!(Path::new(&migrated).exists());
    }

    // --- Second open skips migration ---

    #[test]
    fn second_open_skips_migration() {
        let temp = tempdir().unwrap();
        let layout = test_layout(temp.path());
        setup_dirs(&layout);

        // First open — creates empty DB
        {
            let db = StateDb::open_for_layout(&layout).unwrap();
            let sess = interactive_session(
                3,
                1000,
                2000,
                1,
                Some("ses_FIRST"),
                crate::state::session::SessionMode::General,
            );
            session::write(db.conn(), &sess).unwrap();
        }

        // Second open — should NOT re-initialize or lose data
        let db = StateDb::open_for_layout(&layout).unwrap();
        let loaded = session::read(db.conn())
            .unwrap()
            .expect("session persisted");
        assert_eq!(loaded.session_id.as_deref(), Some("ses_FIRST"));
    }

    // --- Regeneration: deleted state.db starts fresh ---

    #[test]
    fn deleted_state_db_regenerates_cleanly() {
        let temp = tempdir().unwrap();
        let layout = test_layout(temp.path());
        setup_dirs(&layout);

        // Create and populate
        {
            let db = StateDb::open_for_layout(&layout).unwrap();
            session::write(
                db.conn(),
                &interactive_session(
                    3,
                    1000,
                    2000,
                    1,
                    Some("ses_GONE"),
                    crate::state::session::SessionMode::General,
                ),
            )
            .unwrap();
        }

        // Delete the DB
        fs::remove_file(layout.state_db_path()).unwrap();

        // Reopen — should create fresh empty DB, not crash
        let db = StateDb::open_for_layout(&layout).unwrap();
        assert!(session::read(db.conn()).unwrap().is_none());

        // Should be functional
        session::write(
            db.conn(),
            &interactive_session(
                3,
                3000,
                4000,
                1,
                Some("ses_NEW"),
                crate::state::session::SessionMode::General,
            ),
        )
        .unwrap();
        let loaded = session::read(db.conn()).unwrap().expect("fresh session");
        assert_eq!(loaded.session_id.as_deref(), Some("ses_NEW"));
    }

    // --- Session lifecycle: start → increment → stale reset ---

    #[test]
    fn session_lifecycle_start_increment_stale_reset() {
        let temp = tempdir().unwrap();
        let layout = test_layout(temp.path());
        setup_dirs(&layout);

        let db = StateDb::open_for_layout(&layout).unwrap();
        let now = 1_000_000u64;

        // Fresh start
        let state1 = interactive_session(
            3,
            now,
            now,
            1,
            Some("ses_START"),
            crate::state::session::SessionMode::General,
        );
        session::write(db.conn(), &state1).unwrap();

        // Non-stale — should get session ID
        let sid = session::load_session_id(db.conn(), now + 100).unwrap();
        assert_eq!(sid.as_deref(), Some("ses_START"));

        // Stale — should get None
        let stale_sid = session::load_session_id(db.conn(), now + 8 * 3600 + 1).unwrap();
        assert!(stale_sid.is_none());
    }

    // --- Escalation lifecycle: insert → clear non-blocking → clear all ---

    #[test]
    fn escalation_lifecycle() {
        let temp = tempdir().unwrap();
        let layout = test_layout(temp.path());
        setup_dirs(&layout);

        let db = StateDb::open_for_layout(&layout).unwrap();

        // Insert blocking + non-blocking
        escalation::insert(
            db.conn(),
            &EscalationEntry {
                id: "esc_B1".to_owned(),
                kind: EscalationKind::Blocking,
                reason: "critical".to_owned(),
                created_at_epoch_s: 1000,
                session_id: Some("ses_1".to_owned()),
            },
        )
        .unwrap();
        escalation::insert(
            db.conn(),
            &EscalationEntry {
                id: "esc_NB1".to_owned(),
                kind: EscalationKind::NonBlocking,
                reason: "info".to_owned(),
                created_at_epoch_s: 2000,
                session_id: Some("ses_1".to_owned()),
            },
        )
        .unwrap();
        escalation::insert(
            db.conn(),
            &EscalationEntry {
                id: "esc_NB2".to_owned(),
                kind: EscalationKind::NonBlocking,
                reason: "info 2".to_owned(),
                created_at_epoch_s: 3000,
                session_id: None,
            },
        )
        .unwrap();

        assert!(escalation::has_blocking(db.conn()).unwrap());
        assert_eq!(escalation::list(db.conn()).unwrap().len(), 3);

        // Clear non-blocking (stale reset behavior)
        let cleared = escalation::clear_non_blocking(db.conn()).unwrap();
        assert_eq!(cleared, 2);
        assert!(escalation::has_blocking(db.conn()).unwrap());
        assert_eq!(escalation::list(db.conn()).unwrap().len(), 1);

        // Clear all (session boundary behavior)
        escalation::clear_all(db.conn()).unwrap();
        assert!(!escalation::has_blocking(db.conn()).unwrap());
        assert!(escalation::list(db.conn()).unwrap().is_empty());
    }

    // --- Handoff overwrite preserves lifecycle values ---

    #[test]
    fn handoff_preserves_inactive_items() {
        let temp = tempdir().unwrap();
        let layout = test_layout(temp.path());
        setup_dirs(&layout);

        let db = StateDb::open_for_layout(&layout).unwrap();

        let ho = RuntimeHandoffState {
            title: "Mixed lifecycle".to_owned(),
            immediate_actions: vec![
                RuntimeHandoffItem {
                    text: "Active action.".to_owned(),
                    lifecycle: RuntimeLifecycle::Active,
                },
                RuntimeHandoffItem {
                    text: "Archived action.".to_owned(),
                    lifecycle: RuntimeLifecycle::Inactive,
                },
            ],
            ..RuntimeHandoffState::default()
        };

        handoff::write(db.conn(), &ho).unwrap();
        let loaded = handoff::read(db.conn()).unwrap().expect("handoff");

        assert_eq!(loaded.immediate_actions.len(), 2);
        assert_eq!(
            loaded.immediate_actions[0].lifecycle,
            RuntimeLifecycle::Active
        );
        assert_eq!(
            loaded.immediate_actions[1].lifecycle,
            RuntimeLifecycle::Inactive
        );
    }

    // --- Fail-closed: unwritable path ---

    #[test]
    fn open_fails_cleanly_on_unwritable_path() {
        // Attempt to open in a non-existent deeply nested path that we can't create
        // (root-owned directory). This is a best-effort test — skip if running as root.
        let result = StateDb::open(Path::new("/proc/nonexistent/state.db"));
        let err_msg = match result {
            Err(e) => e.to_string(),
            Ok(_) => panic!("expected error for unwritable path"),
        };
        assert!(
            err_msg.contains("state.db"),
            "error should reference state.db: {err_msg}"
        );
    }
}