agent-doc-flow 0.34.69

Pure flow vocabulary and outcome contracts for agent-doc
Documentation
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
use serde::{Deserialize, Serialize};
use std::fmt;

pub const BINARY_OUTCOME_CONTRACT_VERSION: &str = "binary-outcome-v1";
pub const USER_FACING_OUTCOME_CONTRACT_VERSION: &str = "ui-outcome-v1";

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BinaryOutcomeClass {
    Ok,
    Recoverable,
    Blocked,
    Operator,
}

impl BinaryOutcomeClass {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Ok => "ok",
            Self::Recoverable => "recoverable",
            Self::Blocked => "blocked",
            Self::Operator => "operator",
        }
    }
}

impl fmt::Display for BinaryOutcomeClass {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UserFacingOutcomeKind {
    QueuedBehindOwner,
    RecoveredAndRetried,
    DeferredForOperatorProof,
    /// The in-session loop has no drainable head, but a `[focused-cycle]` head
    /// remains that the SUPERVISOR clear-and-continue path will drain (force
    /// `/clear` + re-dispatch to a fresh context). No operator action is required;
    /// the in-session agent simply ends its turn so the supervisor takes over
    /// (`#qfocsup`).
    DeferredForSupervisorDrain,
    /// `#turnsaferecycle` Goal 3 — the hosting supervisor is running a stale binary,
    /// so the current turn phase (preflight / route / stream / session-check / write)
    /// skips its doomed IPC write, schedules the recycle (forced PCP recycle +
    /// supervisor recycle-request), and defers uniformly instead of each phase
    /// thrashing the buffer. No operator action is required; the recycle promotes the
    /// fresh binary at the next idle boundary and the phase re-runs cleanly.
    DeferredForRecycle,
    NoDrainableWork,
    RealComponentConflict,
    BlockedWithExactUnblocker,
}

impl UserFacingOutcomeKind {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::QueuedBehindOwner => "queued_behind_owner",
            Self::RecoveredAndRetried => "recovered_and_retried",
            Self::DeferredForOperatorProof => "deferred_for_operator_proof",
            Self::DeferredForSupervisorDrain => "deferred_for_supervisor_drain",
            Self::DeferredForRecycle => "deferred_for_recycle",
            Self::NoDrainableWork => "no_drainable_work",
            Self::RealComponentConflict => "real_component_conflict",
            Self::BlockedWithExactUnblocker => "blocked_with_exact_unblocker",
        }
    }

    pub const fn class(self) -> BinaryOutcomeClass {
        match self {
            Self::QueuedBehindOwner
            | Self::NoDrainableWork
            | Self::DeferredForSupervisorDrain
            | Self::DeferredForRecycle => BinaryOutcomeClass::Ok,
            Self::RecoveredAndRetried => BinaryOutcomeClass::Recoverable,
            Self::DeferredForOperatorProof => BinaryOutcomeClass::Operator,
            Self::RealComponentConflict | Self::BlockedWithExactUnblocker => {
                BinaryOutcomeClass::Blocked
            }
        }
    }

    pub const fn next_action(self) -> &'static str {
        match self {
            Self::QueuedBehindOwner => "wait_for_owner_turn_to_drain",
            Self::RecoveredAndRetried => "continue_after_recovery_retry",
            Self::DeferredForOperatorProof => "operator_proof_required",
            Self::DeferredForSupervisorDrain => "yield_to_supervisor_clear_and_continue",
            Self::DeferredForRecycle => "yield_for_supervisor_recycle",
            Self::NoDrainableWork => "no_agent_action",
            Self::RealComponentConflict => "resolve_component_conflict",
            Self::BlockedWithExactUnblocker => "follow_unblocker",
        }
    }
}

impl fmt::Display for UserFacingOutcomeKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UserFacingOutcome {
    pub contract_version: String,
    pub outcome: UserFacingOutcomeKind,
    pub class: BinaryOutcomeClass,
    pub next_action: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unblocker: Option<String>,
}

impl UserFacingOutcome {
    pub fn new(outcome: UserFacingOutcomeKind) -> Result<Self, BinaryOutcomeError> {
        if outcome == UserFacingOutcomeKind::BlockedWithExactUnblocker {
            return Err(BinaryOutcomeError::EmptyField { field: "unblocker" });
        }
        Ok(Self {
            contract_version: USER_FACING_OUTCOME_CONTRACT_VERSION.to_string(),
            outcome,
            class: outcome.class(),
            next_action: outcome.next_action().to_string(),
            unblocker: None,
        })
    }

    pub fn with_unblocker(
        outcome: UserFacingOutcomeKind,
        unblocker: impl Into<String>,
    ) -> Result<Self, BinaryOutcomeError> {
        let unblocker = validate_token("unblocker", unblocker.into())?;
        Ok(Self {
            contract_version: USER_FACING_OUTCOME_CONTRACT_VERSION.to_string(),
            outcome,
            class: outcome.class(),
            next_action: outcome.next_action().to_string(),
            unblocker: Some(unblocker),
        })
    }

    pub fn log_fields(&self) -> String {
        let fields = format!(
            "ui_outcome_contract={} ui_outcome={} ui_outcome_class={} next_action={}",
            self.contract_version,
            self.outcome.as_str(),
            self.class.as_str(),
            self.next_action
        );
        match self.unblocker.as_deref() {
            Some(unblocker) => format!("{fields} unblocker={unblocker}"),
            None => fields,
        }
    }
}

pub fn user_outcome_fields(kind: UserFacingOutcomeKind) -> String {
    UserFacingOutcome::new(kind)
        .expect("static user-facing outcome is valid")
        .log_fields()
}

pub fn blocked_with_exact_unblocker_fields(unblocker: &str) -> String {
    UserFacingOutcome::with_unblocker(UserFacingOutcomeKind::BlockedWithExactUnblocker, unblocker)
        .expect("static user-facing unblocker is valid")
        .log_fields()
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BinaryOutcome {
    pub contract_version: String,
    pub class: BinaryOutcomeClass,
    pub invariant_id: String,
    pub proof_marker: String,
    pub next_action: String,
}

impl BinaryOutcome {
    pub fn new(
        class: BinaryOutcomeClass,
        invariant_id: impl Into<String>,
        proof_marker: impl Into<String>,
        next_action: impl Into<String>,
    ) -> Result<Self, BinaryOutcomeError> {
        let invariant_id = validate_token("invariant_id", invariant_id.into())?;
        let proof_marker = validate_token("proof_marker", proof_marker.into())?;
        let next_action = validate_token("next_action", next_action.into())?;
        Ok(Self {
            contract_version: BINARY_OUTCOME_CONTRACT_VERSION.to_string(),
            class,
            invariant_id,
            proof_marker,
            next_action,
        })
    }

    pub fn ok(
        invariant_id: impl Into<String>,
        proof_marker: impl Into<String>,
        next_action: impl Into<String>,
    ) -> Result<Self, BinaryOutcomeError> {
        Self::new(
            BinaryOutcomeClass::Ok,
            invariant_id,
            proof_marker,
            next_action,
        )
    }

    pub fn recoverable(
        invariant_id: impl Into<String>,
        proof_marker: impl Into<String>,
        next_action: impl Into<String>,
    ) -> Result<Self, BinaryOutcomeError> {
        Self::new(
            BinaryOutcomeClass::Recoverable,
            invariant_id,
            proof_marker,
            next_action,
        )
    }

    pub fn blocked(
        invariant_id: impl Into<String>,
        proof_marker: impl Into<String>,
        next_action: impl Into<String>,
    ) -> Result<Self, BinaryOutcomeError> {
        Self::new(
            BinaryOutcomeClass::Blocked,
            invariant_id,
            proof_marker,
            next_action,
        )
    }

    pub fn operator(
        invariant_id: impl Into<String>,
        proof_marker: impl Into<String>,
        next_action: impl Into<String>,
    ) -> Result<Self, BinaryOutcomeError> {
        Self::new(
            BinaryOutcomeClass::Operator,
            invariant_id,
            proof_marker,
            next_action,
        )
    }

    pub fn log_fields(&self) -> String {
        format!(
            "binary_outcome={} invariant={} proof_marker={} next_action={}",
            self.class.as_str(),
            self.invariant_id,
            self.proof_marker,
            self.next_action
        )
    }
}

/// `#turnsaferecycle` Goal 3 — the production emitter for the `supervisor_freshness`
/// binary-outcome contract. A turn phase that short-circuits a doomed IPC write
/// against a stale supervisor (skips the write, schedules the recycle) records this
/// recoverable outcome so the stale→self-recycle→retry contract is attributable in
/// the flow log, not just asserted in a unit test.
pub fn supervisor_stale_self_recycled_outcome() -> BinaryOutcome {
    BinaryOutcome::recoverable(
        "supervisor_freshness",
        "supervisor_binary_stale_self_recycled",
        "restart_supervisor_once_and_retry",
    )
    .expect("static supervisor_freshness outcome tokens are contract-valid")
}

/// `#turnsaferecycle` Goal 3 — the user-facing outcome every turn phase returns when
/// it defers uniformly for a stale-supervisor recycle instead of thrashing the write.
pub fn deferred_for_recycle_outcome() -> UserFacingOutcome {
    UserFacingOutcome::new(UserFacingOutcomeKind::DeferredForRecycle)
        .expect("deferred_for_recycle requires no unblocker")
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BinaryOutcomeError {
    EmptyField { field: &'static str },
    InvalidToken { field: &'static str, value: String },
}

impl fmt::Display for BinaryOutcomeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyField { field } => write!(f, "{field} must not be empty"),
            Self::InvalidToken { field, value } => {
                write!(f, "{field} must be a single field-safe token: {value}")
            }
        }
    }
}

impl std::error::Error for BinaryOutcomeError {}

fn validate_token(field: &'static str, value: String) -> Result<String, BinaryOutcomeError> {
    if value.trim().is_empty() {
        return Err(BinaryOutcomeError::EmptyField { field });
    }
    if value.trim() != value || !value.chars().all(is_token_char) {
        return Err(BinaryOutcomeError::InvalidToken { field, value });
    }
    Ok(value)
}

fn is_token_char(ch: char) -> bool {
    ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-' | '.' | ':' | '/')
}

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

    #[test]
    fn binary_outcome_records_required_contract_fields() {
        let outcome = BinaryOutcome::recoverable(
            "supervisor_freshness",
            "supervisor_binary_stale_self_recycled",
            "restart_supervisor_once_and_retry",
        )
        .unwrap();

        assert_eq!(outcome.contract_version, "binary-outcome-v1");
        assert_eq!(outcome.class, BinaryOutcomeClass::Recoverable);
        assert_eq!(outcome.invariant_id, "supervisor_freshness");
        assert_eq!(
            outcome.log_fields(),
            "binary_outcome=recoverable invariant=supervisor_freshness proof_marker=supervisor_binary_stale_self_recycled next_action=restart_supervisor_once_and_retry"
        );
    }

    #[test]
    fn supervisor_stale_self_recycled_and_deferred_for_recycle_emitters_are_contract_valid() {
        // `#turnsaferecycle` Goal 3: the real emitters (not test-only inline
        // constructions) produce the supervisor_freshness recoverable contract and
        // the deferred_for_recycle user-facing outcome.
        let binary = supervisor_stale_self_recycled_outcome();
        assert_eq!(binary.class, BinaryOutcomeClass::Recoverable);
        assert_eq!(binary.invariant_id, "supervisor_freshness");
        assert_eq!(binary.proof_marker, "supervisor_binary_stale_self_recycled");
        assert_eq!(binary.next_action, "restart_supervisor_once_and_retry");

        let ui = deferred_for_recycle_outcome();
        assert_eq!(ui.outcome, UserFacingOutcomeKind::DeferredForRecycle);
        assert_eq!(ui.class, BinaryOutcomeClass::Ok);
        assert_eq!(ui.next_action, "yield_for_supervisor_recycle");
    }

    #[test]
    fn binary_outcome_classes_are_stable_snake_case() {
        assert_eq!(BinaryOutcomeClass::Ok.as_str(), "ok");
        assert_eq!(BinaryOutcomeClass::Recoverable.as_str(), "recoverable");
        assert_eq!(BinaryOutcomeClass::Blocked.as_str(), "blocked");
        assert_eq!(BinaryOutcomeClass::Operator.as_str(), "operator");

        let json = serde_json::to_value(
            BinaryOutcome::operator(
                "two_editor_convergence",
                "missing_live_vscode_ack",
                "request_operator_live_proof",
            )
            .unwrap(),
        )
        .unwrap();

        assert_eq!(json["class"], "operator");
        assert_eq!(json["next_action"], "request_operator_live_proof");
    }

    #[test]
    fn user_facing_outcome_vocabulary_is_stable_and_typed() {
        use UserFacingOutcomeKind as Kind;

        let cases = [
            (
                Kind::QueuedBehindOwner,
                "queued_behind_owner",
                BinaryOutcomeClass::Ok,
                "wait_for_owner_turn_to_drain",
            ),
            (
                Kind::RecoveredAndRetried,
                "recovered_and_retried",
                BinaryOutcomeClass::Recoverable,
                "continue_after_recovery_retry",
            ),
            (
                Kind::DeferredForOperatorProof,
                "deferred_for_operator_proof",
                BinaryOutcomeClass::Operator,
                "operator_proof_required",
            ),
            (
                Kind::DeferredForSupervisorDrain,
                "deferred_for_supervisor_drain",
                BinaryOutcomeClass::Ok,
                "yield_to_supervisor_clear_and_continue",
            ),
            (
                Kind::DeferredForRecycle,
                "deferred_for_recycle",
                BinaryOutcomeClass::Ok,
                "yield_for_supervisor_recycle",
            ),
            (
                Kind::NoDrainableWork,
                "no_drainable_work",
                BinaryOutcomeClass::Ok,
                "no_agent_action",
            ),
            (
                Kind::RealComponentConflict,
                "real_component_conflict",
                BinaryOutcomeClass::Blocked,
                "resolve_component_conflict",
            ),
            (
                Kind::BlockedWithExactUnblocker,
                "blocked_with_exact_unblocker",
                BinaryOutcomeClass::Blocked,
                "follow_unblocker",
            ),
        ];

        for (kind, token, class, next_action) in cases {
            assert_eq!(kind.as_str(), token);
            assert_eq!(kind.class(), class);
            assert_eq!(kind.next_action(), next_action);
        }

        let json = serde_json::to_value(
            UserFacingOutcome::new(Kind::QueuedBehindOwner)
                .expect("queued outcome does not require an unblocker"),
        )
        .unwrap();
        assert_eq!(json["contract_version"], "ui-outcome-v1");
        assert_eq!(json["outcome"], "queued_behind_owner");
        assert_eq!(json["class"], "ok");
        assert_eq!(json["next_action"], "wait_for_owner_turn_to_drain");
    }

    #[test]
    fn blocked_user_facing_outcome_requires_exact_unblocker() {
        use UserFacingOutcomeKind as Kind;

        assert_eq!(
            UserFacingOutcome::new(Kind::BlockedWithExactUnblocker).unwrap_err(),
            BinaryOutcomeError::EmptyField { field: "unblocker" }
        );

        let outcome = UserFacingOutcome::with_unblocker(
            Kind::BlockedWithExactUnblocker,
            "restore_idle_prompt",
        )
        .unwrap();
        assert_eq!(
            outcome.log_fields(),
            "ui_outcome_contract=ui-outcome-v1 ui_outcome=blocked_with_exact_unblocker ui_outcome_class=blocked next_action=follow_unblocker unblocker=restore_idle_prompt"
        );
        assert!(matches!(
            UserFacingOutcome::with_unblocker(
                Kind::BlockedWithExactUnblocker,
                "restore idle prompt"
            )
            .unwrap_err(),
            BinaryOutcomeError::InvalidToken {
                field: "unblocker",
                ..
            }
        ));
    }

    #[test]
    fn user_outcome_field_helpers_emit_contract_fields() {
        use UserFacingOutcomeKind as Kind;

        assert_eq!(
            user_outcome_fields(Kind::QueuedBehindOwner),
            "ui_outcome_contract=ui-outcome-v1 ui_outcome=queued_behind_owner ui_outcome_class=ok next_action=wait_for_owner_turn_to_drain"
        );
        assert_eq!(
            blocked_with_exact_unblocker_fields("run_recovery_command"),
            "ui_outcome_contract=ui-outcome-v1 ui_outcome=blocked_with_exact_unblocker ui_outcome_class=blocked next_action=follow_unblocker unblocker=run_recovery_command"
        );
    }

    #[test]
    fn binary_outcome_rejects_ambiguous_or_multi_action_fields() {
        assert_eq!(
            BinaryOutcome::ok("", "proof", "continue").unwrap_err(),
            BinaryOutcomeError::EmptyField {
                field: "invariant_id"
            }
        );

        assert!(matches!(
            BinaryOutcome::blocked("queue head", "proof", "stop").unwrap_err(),
            BinaryOutcomeError::InvalidToken {
                field: "invariant_id",
                ..
            }
        ));

        assert!(matches!(
            BinaryOutcome::recoverable("queue_head", "proof", "retry,clear").unwrap_err(),
            BinaryOutcomeError::InvalidToken {
                field: "next_action",
                ..
            }
        ));
    }
}