polyc-controller 2026.8.3

Conversation CRD + kube reconciler for the polychrome control plane.
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
#![allow(clippy::pedantic, clippy::nursery, missing_docs)]

use super::*;
use crate::routine::{RoutinePayload, RoutineProvenance, RoutineScope, RoutineSuspend};

fn provenance() -> RoutineProvenance {
    RoutineProvenance {
        creator_persona: "persona-1".to_owned(),
        conversation_id: "conv-1".to_owned(),
    }
}

/// A minimal, valid spec: private scope (the default), a cron schedule, a
/// non-empty prompt.
fn valid_spec() -> RoutineSpec {
    RoutineSpec {
        description: Some("daily greeting".to_owned()),
        scope: RoutineScope::Private,
        schedule: RoutineSchedule::Cron {
            expression: "0 9 * * *".to_owned(),
            timezone: None,
        },
        payload: RoutinePayload {
            prompt: "Post a short good-morning message to the team channel.".to_owned(),
        },
        provenance: provenance(),
        suspend: None,
    }
}

fn routine(spec: RoutineSpec) -> Routine {
    let mut r = Routine::new("greeting", spec);
    r.metadata.namespace = Some("polychrome".to_owned());
    r.metadata.uid = Some("uid-1".to_owned());
    r
}

#[test]
fn validate_spec_accepts_the_worked_example() {
    assert_eq!(validate_spec(&valid_spec()), Ok(()));
}

#[test]
fn plan_applies_the_worked_example() {
    assert_eq!(plan(&routine(valid_spec())), RoutineAction::Apply);
}

// ── payload (#1591, acceptance criterion 1) ─────────────────────────────

#[test]
fn validate_spec_rejects_an_empty_prompt() {
    let mut spec = valid_spec();
    spec.payload.prompt = String::new();
    let err = validate_spec(&spec).unwrap_err();
    assert!(err.contains("payload.prompt"), "{err}");
}

#[test]
fn validate_spec_rejects_a_whitespace_only_prompt() {
    let mut spec = valid_spec();
    spec.payload.prompt = "   \n\t  ".to_owned();
    let err = validate_spec(&spec).unwrap_err();
    assert!(err.contains("payload.prompt"), "{err}");
}

// ── scope (#1802, acceptance criteria 1 and 2) ──────────────────────────

#[test]
fn validate_spec_accepts_private_scope() {
    let mut spec = valid_spec();
    spec.scope = RoutineScope::Private;
    assert_eq!(validate_spec(&spec), Ok(()));
}

#[test]
fn validate_spec_accepts_public_scope() {
    let mut spec = valid_spec();
    spec.scope = RoutineScope::Public;
    assert_eq!(validate_spec(&spec), Ok(()));
}

/// The retired reserved values (`instance`/`persona`/`shared`) never even
/// reach [`validate_spec`] — they are rejected at deserialize time, since
/// the wire enum no longer names them. See
/// `crate::routine::tests::scope_rejects_the_retired_reserved_values`.
#[test]
fn old_reserved_scope_values_fail_to_deserialize_before_validation() {
    for raw in ["instance", "persona", "shared"] {
        let yaml = serde_json::json!({
            "scope": raw,
            "schedule": { "cron": { "expression": "0 9 * * *" } },
            "payload": { "prompt": "hi" },
            "provenance": { "creatorPersona": "persona-1", "conversationId": "conv-1" },
        });
        assert!(
            serde_json::from_value::<RoutineSpec>(yaml).is_err(),
            "{raw} must fail to deserialize, not reach validate_spec"
        );
    }
}

// ── structured schedule (#1488, acceptance criterion 2) ─────────────────

#[test]
fn validate_spec_rejects_bad_cron_expression() {
    let mut spec = valid_spec();
    spec.schedule = RoutineSchedule::Cron {
        expression: "not a cron expression".to_owned(),
        timezone: None,
    };
    let err = validate_spec(&spec).unwrap_err();
    assert!(err.contains("not a valid cron expression"), "{err}");
}

#[test]
fn validate_spec_rejects_a_bogus_timezone() {
    let mut spec = valid_spec();
    spec.schedule = RoutineSchedule::Cron {
        expression: "0 9 * * *".to_owned(),
        timezone: Some("Not/AZone".to_owned()),
    };
    let err = validate_spec(&spec).unwrap_err();
    assert!(err.contains("Not/AZone"), "{err}");
}

// ── day-of-week translation (#1644) ──────────────────────────────────────
//
// Standard cron's `0` (Sunday) is out of `saffron`'s own 1-7 range, so before
// `normalize_cron_dow` ran ahead of every parse it was rejected here even
// though it is exactly what the "standard five-field cron expression" this
// tool's own contract promises allows.

#[test]
fn validate_spec_accepts_standard_cron_sunday_zero() {
    let mut spec = valid_spec();
    spec.schedule = RoutineSchedule::Cron {
        expression: "0 9 * * 0".to_owned(),
        timezone: None,
    };
    assert_eq!(validate_spec(&spec), Ok(()));
}

#[test]
fn validate_spec_accepts_standard_cron_sunday_seven() {
    let mut spec = valid_spec();
    spec.schedule = RoutineSchedule::Cron {
        expression: "0 9 * * 7".to_owned(),
        timezone: None,
    };
    assert_eq!(validate_spec(&spec), Ok(()));
}

#[test]
fn validate_spec_accepts_a_standard_cron_weekday_range() {
    let mut spec = valid_spec();
    spec.schedule = RoutineSchedule::Cron {
        expression: "30 11 * * 1-5".to_owned(),
        timezone: None,
    };
    assert_eq!(validate_spec(&spec), Ok(()));
}

#[test]
fn validate_spec_still_rejects_a_day_of_week_value_out_of_range_either_way() {
    let mut spec = valid_spec();
    spec.schedule = RoutineSchedule::Cron {
        expression: "0 9 * * 8".to_owned(),
        timezone: None,
    };
    let err = validate_spec(&spec).unwrap_err();
    assert!(err.contains("not a valid cron expression"), "{err}");
}

#[test]
fn validate_spec_accepts_a_once_schedule() {
    let mut spec = valid_spec();
    spec.schedule = RoutineSchedule::Once {
        at: "2026-08-01T15:00:00Z".to_owned(),
    };
    assert_eq!(validate_spec(&spec), Ok(()));
}

#[test]
fn validate_spec_rejects_a_bad_once_instant() {
    let mut spec = valid_spec();
    spec.schedule = RoutineSchedule::Once {
        at: "not-a-timestamp".to_owned(),
    };
    let err = validate_spec(&spec).unwrap_err();
    assert!(err.contains("not-a-timestamp"), "{err}");
    assert!(err.contains("RFC3339"), "{err}");
}

// A bare-string `schedule` is a wire-shape rejection (deserialization fails
// before this validator ever runs) — covered by `routine.rs`'s
// `bare_string_schedule_is_rejected_not_migrated`. This module's validator
// only ever sees a well-typed `RoutineSchedule`.

// ── suspend pause metadata (#1493) ──────────────────────────────────────

#[test]
fn validate_spec_accepts_no_suspend_at_all() {
    let spec = valid_spec();
    assert_eq!(
        spec.suspend, None,
        "the worked example is active by default"
    );
    assert_eq!(validate_spec(&spec), Ok(()));
}

#[test]
fn validate_spec_accepts_a_well_formed_suspend() {
    let mut spec = valid_spec();
    spec.suspend = Some(RoutineSuspend {
        paused_by: "persona-1".to_owned(),
        paused_at: "2026-07-23T00:00:00Z".to_owned(),
        reason: Some("rotating out old announcements".to_owned()),
    });
    assert_eq!(validate_spec(&spec), Ok(()));
}

#[test]
fn validate_spec_accepts_a_suspend_with_no_reason() {
    let mut spec = valid_spec();
    spec.suspend = Some(RoutineSuspend {
        paused_by: "persona-1".to_owned(),
        paused_at: "2026-07-23T00:00:00Z".to_owned(),
        reason: None,
    });
    assert_eq!(validate_spec(&spec), Ok(()));
}

#[test]
fn validate_spec_rejects_an_empty_paused_by() {
    let mut spec = valid_spec();
    spec.suspend = Some(RoutineSuspend {
        paused_by: "   ".to_owned(),
        paused_at: "2026-07-23T00:00:00Z".to_owned(),
        reason: None,
    });
    let err = validate_spec(&spec).unwrap_err();
    assert!(err.contains("pausedBy"), "{err}");
}

#[test]
fn validate_spec_rejects_a_bad_paused_at_instant() {
    let mut spec = valid_spec();
    spec.suspend = Some(RoutineSuspend {
        paused_by: "persona-1".to_owned(),
        paused_at: "not-a-timestamp".to_owned(),
        reason: None,
    });
    let err = validate_spec(&spec).unwrap_err();
    assert!(err.contains("not-a-timestamp"), "{err}");
    assert!(err.contains("RFC3339"), "{err}");
}

/// The checked-in example manifest, parsed straight from the repo file, so
/// the example can never silently drift out of validity.
///
/// Routes through a `serde_json::Value` intermediate rather than parsing
/// straight from YAML into [`RoutineSpec`]: unlike `serde_json`,
/// `serde_yaml_ng`'s externally tagged enum support requires YAML's native
/// tag syntax (`!Cron {...}`), not the plain `cron: {...}` mapping this
/// schema's `RoutineSchedule` actually uses on the wire — a `serde_yaml_ng`
/// limitation with no bearing on the real admission path (the API server
/// always converts YAML to JSON before validating against the OpenAPI
/// schema, so `kubectl apply` of this exact file works today).
#[test]
fn validate_spec_accepts_the_checked_in_greeting_example() {
    let yaml = include_str!("../../../../manifests/examples/greeting/routine.yaml"); // test-fixture-allow: #1369 — this test's whole point is guarding the checked-in reference example against drift, mirroring the conformance-vectors precedent in scripts/test-fixture-baseline.txt
    let doc: serde_yaml_ng::Value = serde_yaml_ng::from_str(yaml).expect("valid YAML");
    let spec_value = doc.get("spec").expect("spec key").clone();
    let json = serde_json::to_value(spec_value).expect("yaml value converts to json value");
    let spec: RoutineSpec = serde_json::from_value(json).expect("spec deserializes");
    assert_eq!(validate_spec(&spec), Ok(()));
    assert_eq!(spec.scope, RoutineScope::Private);
}

#[test]
fn plan_reports_invalid_with_the_specific_reason() {
    let mut spec = valid_spec();
    spec.payload.prompt = String::new();
    match plan(&routine(spec)) {
        RoutineAction::Invalid(reason) => {
            assert!(reason.contains("payload.prompt"), "{reason}");
        }
        other => panic!("expected Invalid, got {other:?}"),
    }
}

#[test]
fn deleting_routine_plans_noop() {
    let mut r = routine(valid_spec());
    r.metadata.deletion_timestamp = Some(k8s_openapi::apimachinery::pkg::apis::meta::v1::Time(
        "2026-06-10T00:00:00Z".parse().unwrap(),
    ));
    assert_eq!(plan(&r), RoutineAction::Noop);
}

#[test]
fn reconcile_apply_plans_apply_for_a_valid_spec() {
    assert_eq!(plan(&routine(valid_spec())), RoutineAction::Apply);
}

/// A hand-rolled fake `kube::Client`, so the Apply branch's live DELETE
/// calls are exercised through the real [`reconcile`] dispatcher rather than
/// only through the pure [`plan`] decision. Mirrors `crate::reconcile`'s own
/// `fake_conversations` `tower::service_fn` pattern (that module's doc
/// explains why: no reusable kube-API mock exists in this crate, and the
/// live-cluster `e2e` feature is out of scope for a fast unit test). Records
/// every request's `(method, path)`. The two `GET`s return legacy children
/// owned by this exact Routine UID, `DELETE` returns a Kubernetes `Status`,
/// and the final status `PATCH` echoes a minimally valid `Routine`.
mod fake_routines {
    use std::sync::{Arc, Mutex};

    use http::{Method, StatusCode};

    /// One observed request: its method and request path.
    #[derive(Debug, Clone, PartialEq, Eq)]
    pub(super) struct Observed {
        pub(super) method: Method,
        pub(super) path: String,
    }

    pub(super) fn client(
        requests: Arc<Mutex<Vec<Observed>>>,
        child_owner_uid: &'static str,
    ) -> kube::Client {
        let svc = tower::service_fn(move |req: http::Request<kube::client::Body>| {
            let requests = requests.clone();
            async move {
                let method = req.method().clone();
                let path = req.uri().path().to_owned();
                requests
                    .lock()
                    .expect("requests lock poisoned")
                    .push(Observed {
                        method: method.clone(),
                        path: path.clone(),
                    });
                let payload = if method == Method::GET && path.contains("/serviceaccounts/") {
                    serde_json::to_vec(&serde_json::json!({
                        "apiVersion": "v1",
                        "kind": "ServiceAccount",
                        "metadata": {
                            "name": "greeting-trigger",
                            "uid": "sa-uid",
                            "resourceVersion": "sa-rv",
                            "ownerReferences": [{
                                "apiVersion": "polychrome.dev/v1alpha1",
                                "kind": "Routine",
                                "name": "greeting",
                                "uid": child_owner_uid,
                                "controller": true,
                            }],
                        },
                    }))
                    .unwrap()
                } else if method == Method::GET && path.contains("/cronjobs/") {
                    serde_json::to_vec(&serde_json::json!({
                        "apiVersion": "batch/v1",
                        "kind": "CronJob",
                        "metadata": {
                            "name": "greeting",
                            "uid": "cron-uid",
                            "resourceVersion": "cron-rv",
                            "ownerReferences": [{
                                "apiVersion": "polychrome.dev/v1alpha1",
                                "kind": "Routine",
                                "name": "greeting",
                                "uid": child_owner_uid,
                                "controller": true,
                            }],
                        },
                    }))
                    .unwrap()
                } else if method == Method::DELETE {
                    serde_json::to_vec(&serde_json::json!({
                        "apiVersion": "v1",
                        "kind": "Status",
                        "status": "Success",
                    }))
                    .unwrap()
                } else {
                    serde_json::to_vec(&serde_json::json!({
                        "apiVersion": "polychrome.dev/v1alpha1",
                        "kind": "Routine",
                        "metadata": { "name": "greeting" },
                        "spec": {
                            "scope": "private",
                            "schedule": { "cron": { "expression": "0 9 * * *" } },
                            "payload": {
                                "prompt": "Post a short good-morning message to the team channel.",
                            },
                            "provenance": {
                                "creatorPersona": "persona-1",
                                "conversationId": "conv-1",
                            },
                        },
                        "status": {},
                    }))
                    .unwrap()
                };
                let resp = http::Response::builder()
                    .status(StatusCode::OK)
                    .header("content-type", "application/json")
                    .body(kube::client::Body::from(payload))
                    .expect("build fake response");
                Ok::<_, std::convert::Infallible>(resp)
            }
        });
        kube::Client::new(svc, "polychrome")
    }
}

/// A valid routine's `reconcile` pass reads and deletes both legacy children,
/// and never PATCH-applies either (#1371). The reads supply the target UID and
/// resource version for the delete preconditions and prove that the child is
/// owned by this Routine incarnation.
#[tokio::test]
async fn reconcile_deletes_both_legacy_children_never_applies() {
    let requests = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
    let client = fake_routines::client(requests.clone(), "uid-1");
    let ctx = std::sync::Arc::new(Context { client });
    let r = std::sync::Arc::new(routine(valid_spec()));

    let action = reconcile(r, ctx).await.expect("reconcile succeeds");
    assert_eq!(
        action,
        Action::await_change(),
        "nothing owned, so nothing to periodically requeue for"
    );

    let seen = requests.lock().expect("lock").clone();
    let deletes: Vec<_> = seen
        .iter()
        .filter(|r| r.method == http::Method::DELETE)
        .collect();
    assert_eq!(deletes.len(), 2, "exactly one DELETE per child: {seen:?}");
    assert!(
        deletes
            .iter()
            .any(|r| r.path.ends_with("/serviceaccounts/greeting-trigger")),
        "deletes the per-routine trigger ServiceAccount: {seen:?}"
    );
    assert!(
        deletes
            .iter()
            .any(|r| r.path.ends_with("/cronjobs/greeting")),
        "deletes the routine's own-named CronJob: {seen:?}"
    );
    assert!(
        seen.iter()
            .all(|r| r.method != http::Method::PATCH || r.path.ends_with("/status")),
        "the only non-DELETE call is the status patch, never an apply of either child: {seen:?}"
    );
}

#[tokio::test]
async fn reconcile_refuses_to_delete_foreign_same_named_legacy_children() {
    let requests = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
    let client = fake_routines::client(requests.clone(), "prior-routine-uid");
    let ctx = std::sync::Arc::new(Context { client });

    reconcile(std::sync::Arc::new(routine(valid_spec())), ctx)
        .await
        .expect("foreign legacy children are skipped");

    let seen = requests.lock().expect("lock");
    assert!(
        seen.iter()
            .all(|request| request.method != http::Method::DELETE),
        "a current Routine must not delete a prior or foreign owner's same-named resource: {seen:?}"
    );
}

#[test]
fn legacy_delete_is_pinned_to_the_observed_owned_incarnation() {
    let mut routine = routine(valid_spec());
    routine.metadata.uid = Some("routine-uid".to_owned());
    let mut child = k8s_openapi::api::batch::v1::CronJob::default();
    child.metadata.name = Some("greeting".to_owned());
    child.metadata.uid = Some("cron-uid".to_owned());
    child.metadata.resource_version = Some("cron-rv".to_owned());
    child.metadata.owner_references = routine.controller_owner_ref(&()).map(|owner| vec![owner]);

    let params = legacy_delete_params(&routine, &child).expect("owned live legacy child");
    let preconditions = params.preconditions.expect("delete preconditions");
    assert_eq!(preconditions.uid.as_deref(), Some("cron-uid"));
    assert_eq!(preconditions.resource_version.as_deref(), Some("cron-rv"));

    routine.metadata.uid = Some("replacement-routine".to_owned());
    assert!(
        legacy_delete_params(&routine, &child).is_none(),
        "a recreated routine must not delete the prior incarnation's child"
    );
}