difflore-core 0.2.0

Core library for the difflore CLI — rule store, retrieval, MCP server, hooks, cloud sync. Not intended for direct use; depend on `difflore-cli` instead.
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use sqlx::{Row, SqlitePool};

use crate::memory_autopilot::{
    AutopilotEventInput, DEFAULT_AUTOPILOT_LIMIT, MemoryAutopilotOptions,
    ensure_autopilot_events_table, record_autopilot_event, run_memory_autopilot,
};
use crate::{CoreError, Result};

pub const BACKGROUND_AUTOPILOT_LIMIT: usize = DEFAULT_AUTOPILOT_LIMIT;
pub const BACKGROUND_CURATOR_LIMIT: usize = DEFAULT_AUTOPILOT_LIMIT;
pub const SESSION_END_AUTOPILOT_COOLDOWN_SECS: i64 = 300;
pub const EXPLICIT_AUTOPILOT_COOLDOWN_SECS: i64 = 60;

const BACKGROUND_LEASE_SECS: i64 = 600;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AutopilotScheduleRequest<'a> {
    pub reason: &'a str,
    pub cooldown_secs: i64,
    pub lease_owner: &'a str,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct MemoryAutopilotScheduleStatus {
    pub enabled: bool,
    pub dirty: bool,
    pub last_dirty_at: Option<String>,
    pub last_dirty_reason: Option<String>,
    pub last_trigger_at: Option<String>,
    pub last_trigger_reason: Option<String>,
    pub last_run_at: Option<String>,
    pub lease_owner: Option<String>,
    pub lease_expires_at: Option<String>,
    pub last_result: Value,
    pub trigger_count: i64,
    pub dirty_mark_count: i64,
    pub spawn_attempt_count: i64,
    pub spawn_success_count: i64,
    pub run_count: i64,
    pub productive_run_count: i64,
    pub skip_count: i64,
    pub last_skip_reason: Option<String>,
}

impl Default for MemoryAutopilotScheduleStatus {
    fn default() -> Self {
        Self {
            enabled: true,
            dirty: false,
            last_dirty_at: None,
            last_dirty_reason: None,
            last_trigger_at: None,
            last_trigger_reason: None,
            last_run_at: None,
            lease_owner: None,
            lease_expires_at: None,
            last_result: json!({}),
            trigger_count: 0,
            dirty_mark_count: 0,
            spawn_attempt_count: 0,
            spawn_success_count: 0,
            run_count: 0,
            productive_run_count: 0,
            skip_count: 0,
            last_skip_reason: None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct MemoryAutopilotBackgroundRun {
    pub lease_owner: String,
    pub productive: bool,
    pub enabled_count: usize,
    pub skipped_count: usize,
    pub remaining_auto_enable_groups: usize,
    pub needs_review_groups: usize,
    pub started_at: String,
    pub result: Value,
}

pub async fn ensure_autopilot_schedule_table(pool: &SqlitePool) -> Result<()> {
    sqlx::query(
        "CREATE TABLE IF NOT EXISTS memory_autopilot_schedule (
            id INTEGER PRIMARY KEY CHECK (id = 1),
            enabled INTEGER NOT NULL DEFAULT 1,
            dirty INTEGER NOT NULL DEFAULT 0,
            last_dirty_at TEXT,
            last_dirty_reason TEXT,
            last_trigger_at TEXT,
            last_trigger_reason TEXT,
            last_run_at TEXT,
            lease_owner TEXT,
            lease_expires_at TEXT,
            last_result TEXT NOT NULL DEFAULT '{}',
            trigger_count INTEGER NOT NULL DEFAULT 0,
            dirty_mark_count INTEGER NOT NULL DEFAULT 0,
            spawn_attempt_count INTEGER NOT NULL DEFAULT 0,
            spawn_success_count INTEGER NOT NULL DEFAULT 0,
            run_count INTEGER NOT NULL DEFAULT 0,
            productive_run_count INTEGER NOT NULL DEFAULT 0,
            skip_count INTEGER NOT NULL DEFAULT 0,
            last_skip_reason TEXT
        )",
    )
    .execute(pool)
    .await?;
    sqlx::query("INSERT OR IGNORE INTO memory_autopilot_schedule (id) VALUES (1)")
        .execute(pool)
        .await?;
    Ok(())
}

pub async fn mark_autopilot_dirty(pool: &SqlitePool, reason: &str) -> Result<()> {
    ensure_autopilot_schedule_table(pool).await?;
    sqlx::query(
        "UPDATE memory_autopilot_schedule
         SET dirty = 1,
             last_dirty_at = strftime('%Y-%m-%dT%H:%M:%f', 'now'),
             last_dirty_reason = ?1,
             last_trigger_at = strftime('%Y-%m-%dT%H:%M:%f', 'now'),
             last_trigger_reason = ?1,
             trigger_count = trigger_count + 1,
             dirty_mark_count = dirty_mark_count + 1
         WHERE id = 1",
    )
    .bind(reason)
    .execute(pool)
    .await?;
    Ok(())
}

pub async fn try_acquire_autopilot_lease(
    pool: &SqlitePool,
    request: AutopilotScheduleRequest<'_>,
) -> Result<bool> {
    ensure_autopilot_schedule_table(pool).await?;
    let cooldown = format!("-{} seconds", request.cooldown_secs.max(0));
    let lease_expiry = format!("+{BACKGROUND_LEASE_SECS} seconds");
    let result = sqlx::query(
        "UPDATE memory_autopilot_schedule
         SET lease_owner = ?1,
             lease_expires_at = strftime('%Y-%m-%dT%H:%M:%f', 'now', ?2),
             last_trigger_at = strftime('%Y-%m-%dT%H:%M:%f', 'now'),
             last_trigger_reason = ?3,
             trigger_count = trigger_count + 1,
             spawn_attempt_count = spawn_attempt_count + 1,
             last_skip_reason = NULL
         WHERE id = 1
           AND enabled = 1
           AND dirty = 1
           AND (lease_owner IS NULL OR julianday(lease_expires_at) < julianday('now'))
           AND (last_run_at IS NULL OR julianday(last_run_at) < julianday('now', ?4))",
    )
    .bind(request.lease_owner)
    .bind(lease_expiry)
    .bind(request.reason)
    .bind(&cooldown)
    .execute(pool)
    .await?;

    if result.rows_affected() == 1 {
        return Ok(true);
    }

    record_autopilot_skip(pool, request.reason, &cooldown).await?;
    Ok(false)
}

pub async fn try_acquire_manual_autopilot_lease(
    pool: &SqlitePool,
    lease_owner: &str,
) -> Result<bool> {
    ensure_autopilot_schedule_table(pool).await?;
    let lease_expiry = format!("+{BACKGROUND_LEASE_SECS} seconds");
    let result = sqlx::query(
        "UPDATE memory_autopilot_schedule
         SET lease_owner = ?1,
             lease_expires_at = strftime('%Y-%m-%dT%H:%M:%f', 'now', ?2),
             last_trigger_at = strftime('%Y-%m-%dT%H:%M:%f', 'now'),
             last_trigger_reason = 'manual',
             trigger_count = trigger_count + 1
         WHERE id = 1
           AND (lease_owner IS NULL OR julianday(lease_expires_at) < julianday('now'))",
    )
    .bind(lease_owner)
    .bind(lease_expiry)
    .execute(pool)
    .await?;
    Ok(result.rows_affected() == 1)
}

pub async fn note_autopilot_spawn_success(pool: &SqlitePool, lease_owner: &str) -> Result<()> {
    ensure_autopilot_schedule_table(pool).await?;
    sqlx::query(
        "UPDATE memory_autopilot_schedule
         SET spawn_success_count = spawn_success_count + 1
         WHERE id = 1 AND lease_owner = ?1",
    )
    .bind(lease_owner)
    .execute(pool)
    .await?;
    Ok(())
}

pub async fn release_autopilot_lease(
    pool: &SqlitePool,
    lease_owner: &str,
    reason: &str,
) -> Result<()> {
    ensure_autopilot_schedule_table(pool).await?;
    sqlx::query(
        "UPDATE memory_autopilot_schedule
         SET lease_owner = NULL,
             lease_expires_at = NULL,
             last_skip_reason = ?2
         WHERE id = 1 AND lease_owner = ?1",
    )
    .bind(lease_owner)
    .bind(reason)
    .execute(pool)
    .await?;
    Ok(())
}

pub async fn run_background_memory_autopilot(
    pool: &SqlitePool,
    lease_owner: &str,
) -> Result<MemoryAutopilotBackgroundRun> {
    ensure_autopilot_schedule_table(pool).await?;
    ensure_autopilot_events_table(pool).await?;
    let started_at = sqlite_now(pool).await?;

    let owns_lease = sqlx::query_scalar::<_, i64>(
        "SELECT COUNT(*) FROM memory_autopilot_schedule
         WHERE id = 1 AND lease_owner = ?1 AND julianday(lease_expires_at) >= julianday('now')",
    )
    .bind(lease_owner)
    .fetch_one(pool)
    .await?;
    if owns_lease == 0 {
        return Err(CoreError::Validation(
            "autopilot background lease is not held".to_owned(),
        ));
    }

    let report = run_memory_autopilot(
        pool,
        MemoryAutopilotOptions {
            dry_run: false,
            max_auto_enable: BACKGROUND_AUTOPILOT_LIMIT,
            curator_max_candidates: Some(BACKGROUND_CURATOR_LIMIT),
        },
    )
    .await;

    let run = match report {
        Ok(report) => {
            let enabled_count = report.auto_enabled.len();
            let productive = enabled_count > 0;
            let result = json!({
                "status": "ok",
                "productive": productive,
                "enabledCount": enabled_count,
                "skippedCount": report.skipped.len(),
                "remainingAutoEnableGroups": report.digest.counts.auto_enable_groups,
                "needsReviewGroups": report.digest.counts.needs_review_groups,
                "maxAutoEnable": report.max_auto_enable,
                "startedAt": started_at,
            });
            finish_autopilot_run(pool, lease_owner, &started_at, productive, &result).await?;
            record_autopilot_event(
                pool,
                AutopilotEventInput {
                    event_type: "background_run_finished",
                    rule_id: None,
                    item_ids: &[],
                    group_id: None,
                    title: "Background memory autopilot",
                    reason: if productive {
                        "enabled high-confidence memory"
                    } else {
                        "no high-confidence memory enabled"
                    },
                    payload: result.clone(),
                },
            )
            .await?;
            MemoryAutopilotBackgroundRun {
                lease_owner: lease_owner.to_owned(),
                productive,
                enabled_count,
                skipped_count: report.skipped.len(),
                remaining_auto_enable_groups: report.digest.counts.auto_enable_groups,
                needs_review_groups: report.digest.counts.needs_review_groups,
                started_at,
                result,
            }
        }
        Err(err) => {
            let error_message = err.to_string();
            let result = json!({
                "status": "error",
                "productive": false,
                "error": error_message,
                "startedAt": started_at,
            });
            finish_autopilot_run(pool, lease_owner, &started_at, false, &result).await?;
            record_autopilot_event(
                pool,
                AutopilotEventInput {
                    event_type: "background_run_failed",
                    rule_id: None,
                    item_ids: &[],
                    group_id: None,
                    title: "Background memory autopilot",
                    reason: result
                        .get("error")
                        .and_then(Value::as_str)
                        .unwrap_or("background autopilot failed"),
                    payload: result.clone(),
                },
            )
            .await?;
            return Err(err);
        }
    };

    Ok(run)
}

pub async fn load_autopilot_schedule_status(
    pool: &SqlitePool,
) -> Result<MemoryAutopilotScheduleStatus> {
    ensure_autopilot_schedule_table(pool).await?;
    let row = sqlx::query(
        "SELECT enabled, dirty, last_dirty_at, last_dirty_reason,
                last_trigger_at, last_trigger_reason, last_run_at,
                lease_owner, lease_expires_at, last_result,
                trigger_count, dirty_mark_count, spawn_attempt_count, spawn_success_count,
                run_count, productive_run_count, skip_count, last_skip_reason
         FROM memory_autopilot_schedule
         WHERE id = 1",
    )
    .fetch_one(pool)
    .await?;
    let last_result_raw: String = row.try_get("last_result")?;
    Ok(MemoryAutopilotScheduleStatus {
        enabled: row.try_get::<i64, _>("enabled")? != 0,
        dirty: row.try_get::<i64, _>("dirty")? != 0,
        last_dirty_at: row.try_get("last_dirty_at").ok(),
        last_dirty_reason: row.try_get("last_dirty_reason").ok(),
        last_trigger_at: row.try_get("last_trigger_at").ok(),
        last_trigger_reason: row.try_get("last_trigger_reason").ok(),
        last_run_at: row.try_get("last_run_at").ok(),
        lease_owner: row.try_get("lease_owner").ok(),
        lease_expires_at: row.try_get("lease_expires_at").ok(),
        last_result: serde_json::from_str(&last_result_raw).unwrap_or_else(|_| json!({})),
        trigger_count: row.try_get("trigger_count")?,
        dirty_mark_count: row.try_get("dirty_mark_count")?,
        spawn_attempt_count: row.try_get("spawn_attempt_count")?,
        spawn_success_count: row.try_get("spawn_success_count")?,
        run_count: row.try_get("run_count")?,
        productive_run_count: row.try_get("productive_run_count")?,
        skip_count: row.try_get("skip_count")?,
        last_skip_reason: row.try_get("last_skip_reason").ok(),
    })
}

async fn record_autopilot_skip(pool: &SqlitePool, reason: &str, cooldown: &str) -> Result<()> {
    // The CASE mirrors the acquire predicate in `try_acquire_autopilot_lease` so the recorded
    // reason reflects the same predicate that just failed. The explicit cooldown arm uses the
    // negation of the acquire cooldown clause (last_run_at >= now+cooldown) instead of relying on
    // a catch-all ELSE, so unmodeled failures fall through to 'unknown' rather than mislabelling
    // them as cooldown.
    sqlx::query(
        "UPDATE memory_autopilot_schedule
         SET trigger_count = trigger_count + 1,
             spawn_attempt_count = spawn_attempt_count + 1,
             skip_count = skip_count + 1,
             last_trigger_at = strftime('%Y-%m-%dT%H:%M:%f', 'now'),
             last_trigger_reason = ?1,
             last_skip_reason =
                CASE
                    WHEN enabled = 0 THEN 'disabled'
                    WHEN dirty = 0 THEN 'not_dirty'
                    WHEN lease_owner IS NOT NULL AND julianday(lease_expires_at) >= julianday('now') THEN 'lease_held'
                    WHEN last_run_at IS NOT NULL AND julianday(last_run_at) >= julianday('now', ?2) THEN 'cooldown'
                    ELSE 'unknown'
                END
         WHERE id = 1",
    )
    .bind(reason)
    .bind(cooldown)
    .execute(pool)
    .await?;
    Ok(())
}

async fn finish_autopilot_run(
    pool: &SqlitePool,
    lease_owner: &str,
    started_at: &str,
    productive: bool,
    result: &Value,
) -> Result<()> {
    let result_json = serde_json::to_string(result)?;
    sqlx::query(
        "UPDATE memory_autopilot_schedule
         SET last_run_at = strftime('%Y-%m-%dT%H:%M:%f', 'now'),
             dirty = CASE
                WHEN last_dirty_at IS NULL OR julianday(last_dirty_at) < julianday(?2) THEN 0
                ELSE dirty
             END,
             lease_owner = NULL,
             lease_expires_at = NULL,
             last_result = ?3,
             run_count = run_count + 1,
             productive_run_count = productive_run_count + ?4,
             last_skip_reason = NULL
         WHERE id = 1 AND lease_owner = ?1",
    )
    .bind(lease_owner)
    .bind(started_at)
    .bind(result_json)
    .bind(i64::from(productive))
    .execute(pool)
    .await?;
    Ok(())
}

async fn sqlite_now(pool: &SqlitePool) -> Result<String> {
    Ok(
        sqlx::query_scalar::<_, String>("SELECT strftime('%Y-%m-%dT%H:%M:%f', 'now')")
            .fetch_one(pool)
            .await?,
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
    use std::str::FromStr;

    async fn pool() -> SqlitePool {
        let opts = SqliteConnectOptions::from_str("sqlite::memory:")
            .expect("sqlite opts")
            .create_if_missing(true);
        let pool = SqlitePoolOptions::new()
            .max_connections(1)
            .connect_with(opts)
            .await
            .expect("connect");
        ensure_autopilot_schedule_table(&pool)
            .await
            .expect("ensure table");
        pool
    }

    #[tokio::test]
    async fn lease_acquire_is_atomic_for_dirty_schedule() {
        let pool = pool().await;
        mark_autopilot_dirty(&pool, "test").await.expect("dirty");

        let first = try_acquire_autopilot_lease(
            &pool,
            AutopilotScheduleRequest {
                reason: "session_end",
                cooldown_secs: 0,
                lease_owner: "owner-a",
            },
        )
        .await
        .expect("first");
        let second = try_acquire_autopilot_lease(
            &pool,
            AutopilotScheduleRequest {
                reason: "session_end",
                cooldown_secs: 0,
                lease_owner: "owner-b",
            },
        )
        .await
        .expect("second");

        assert!(first);
        assert!(!second);
        let status = load_autopilot_schedule_status(&pool).await.expect("status");
        assert_eq!(status.lease_owner.as_deref(), Some("owner-a"));
        assert_eq!(status.spawn_attempt_count, 2);
        assert_eq!(status.skip_count, 1);
    }

    #[tokio::test]
    async fn run_started_after_dirty_does_not_clear_new_dirty() {
        let pool = pool().await;
        mark_autopilot_dirty(&pool, "before").await.expect("dirty");
        let acquired = try_acquire_autopilot_lease(
            &pool,
            AutopilotScheduleRequest {
                reason: "session_end",
                cooldown_secs: 0,
                lease_owner: "owner",
            },
        )
        .await
        .expect("acquire");
        assert!(acquired);
        let started_at = sqlite_now(&pool).await.expect("now");
        sqlx::query(
            "UPDATE memory_autopilot_schedule
             SET dirty = 1, last_dirty_at = datetime(?1, '+1 second')
             WHERE id = 1",
        )
        .bind(&started_at)
        .execute(&pool)
        .await
        .expect("new dirty");
        finish_autopilot_run(&pool, "owner", &started_at, false, &json!({"status":"ok"}))
            .await
            .expect("finish");

        let status = load_autopilot_schedule_status(&pool).await.expect("status");
        assert!(status.dirty);
        assert_eq!(status.run_count, 1);
        assert_eq!(status.productive_run_count, 0);
    }

    #[tokio::test]
    async fn run_started_at_same_instant_as_dirty_preserves_dirty() {
        let pool = pool().await;
        mark_autopilot_dirty(&pool, "before").await.expect("dirty");
        let acquired = try_acquire_autopilot_lease(
            &pool,
            AutopilotScheduleRequest {
                reason: "session_end",
                cooldown_secs: 0,
                lease_owner: "owner",
            },
        )
        .await
        .expect("acquire");
        assert!(acquired);
        let started_at = "2026-01-01T00:00:00.500";
        sqlx::query(
            "UPDATE memory_autopilot_schedule
             SET dirty = 1, last_dirty_at = ?1
             WHERE id = 1",
        )
        .bind(started_at)
        .execute(&pool)
        .await
        .expect("same-instant dirty");
        finish_autopilot_run(&pool, "owner", started_at, false, &json!({"status":"ok"}))
            .await
            .expect("finish");

        let status = load_autopilot_schedule_status(&pool).await.expect("status");
        assert!(status.dirty);
        assert_eq!(status.run_count, 1);
    }

    #[tokio::test]
    async fn skip_during_cooldown_records_cooldown_reason() {
        let pool = pool().await;
        mark_autopilot_dirty(&pool, "test").await.expect("dirty");
        let acquired = try_acquire_autopilot_lease(
            &pool,
            AutopilotScheduleRequest {
                reason: "session_end",
                cooldown_secs: 0,
                lease_owner: "owner",
            },
        )
        .await
        .expect("acquire");
        assert!(acquired);
        // Finish the run and re-arm dirty so only the cooldown predicate can block the next
        // acquire. last_run_at is now (set by finish), so a long cooldown keeps us blocked.
        let started_at = sqlite_now(&pool).await.expect("now");
        finish_autopilot_run(&pool, "owner", &started_at, false, &json!({"status":"ok"}))
            .await
            .expect("finish");
        mark_autopilot_dirty(&pool, "again").await.expect("dirty");

        let acquired_again = try_acquire_autopilot_lease(
            &pool,
            AutopilotScheduleRequest {
                reason: "session_end",
                cooldown_secs: 3600,
                lease_owner: "owner-2",
            },
        )
        .await
        .expect("acquire-2");
        assert!(!acquired_again);

        let status = load_autopilot_schedule_status(&pool).await.expect("status");
        assert_eq!(status.last_skip_reason.as_deref(), Some("cooldown"));
    }

    #[tokio::test]
    async fn skip_while_lease_held_records_lease_held_reason() {
        let pool = pool().await;
        mark_autopilot_dirty(&pool, "test").await.expect("dirty");
        let first = try_acquire_autopilot_lease(
            &pool,
            AutopilotScheduleRequest {
                reason: "session_end",
                cooldown_secs: 0,
                lease_owner: "owner-a",
            },
        )
        .await
        .expect("first");
        assert!(first);
        let second = try_acquire_autopilot_lease(
            &pool,
            AutopilotScheduleRequest {
                reason: "session_end",
                cooldown_secs: 0,
                lease_owner: "owner-b",
            },
        )
        .await
        .expect("second");
        assert!(!second);

        let status = load_autopilot_schedule_status(&pool).await.expect("status");
        assert_eq!(status.last_skip_reason.as_deref(), Some("lease_held"));
    }

    #[tokio::test]
    async fn status_surfaces_corrupt_not_null_counters() {
        let pool = pool().await;
        sqlx::query("UPDATE memory_autopilot_schedule SET trigger_count = 'broken' WHERE id = 1")
            .execute(&pool)
            .await
            .expect("corrupt counter");

        let err = load_autopilot_schedule_status(&pool)
            .await
            .expect_err("corrupt counters should not be treated as zero");
        assert!(
            matches!(err, CoreError::Database(_)),
            "expected database decode error, got {err}"
        );
    }

    #[tokio::test]
    async fn expired_lease_can_be_acquired_again() {
        let pool = pool().await;
        mark_autopilot_dirty(&pool, "test").await.expect("dirty");
        let first = try_acquire_autopilot_lease(
            &pool,
            AutopilotScheduleRequest {
                reason: "session_end",
                cooldown_secs: 0,
                lease_owner: "old",
            },
        )
        .await
        .expect("first");
        assert!(first);
        sqlx::query(
            "UPDATE memory_autopilot_schedule
             SET lease_expires_at = datetime('now', '-1 second')
             WHERE id = 1",
        )
        .execute(&pool)
        .await
        .expect("expire");

        let second = try_acquire_autopilot_lease(
            &pool,
            AutopilotScheduleRequest {
                reason: "session_end",
                cooldown_secs: 0,
                lease_owner: "new",
            },
        )
        .await
        .expect("second");
        assert!(second);
        let status = load_autopilot_schedule_status(&pool).await.expect("status");
        assert_eq!(status.lease_owner.as_deref(), Some("new"));
    }
}