yardlet 0.7.0

Yardlet: a local AI workbench. Plan, queue, route, validate, and hand off long-running work using your already-installed Codex and Claude Code CLIs as hidden workers.
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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
//! Canonical Yardlet data model.
//!
//! These structs map to the `.agents/*.yaml` files and the per-run JSON
//! artifacts. Logic-bearing fields are typed; loosely-structured policy detail
//! that Yardlet only passes through to workers is kept as `yaml::Value` so the
//! model does not over-constrain user-edited files.

use serde::{Deserialize, Serialize};

use crate::yaml;

fn default_true() -> bool {
    true
}

fn default_language() -> String {
    "auto".to_string()
}

// ---------------------------------------------------------------------------
// .agents/yard.yaml
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct YardConfig {
    pub schema_version: u32,
    pub product: String,
    pub workspace_id: String,
    pub created_at: String,
    pub state_dir: String,
    pub default_interface: String,
    pub canonical_queue: String,
    pub current_intent: String,
    /// User-facing output language for worker content: "auto" (detect from the
    /// request), "ko", "en", etc. Yardlet's own CLI/TUI chrome stays English.
    #[serde(default = "default_language")]
    pub language: String,
    /// Default worker permission: "sandboxed" (local-only, network blocked) or
    /// "full" (drop the sandbox so commands/network run freely; the worker still
    /// self-gates dangerous actions). Lets a user opt into autonomy once instead
    /// of passing --bypass per run.
    #[serde(default = "default_access")]
    pub default_access: String,
    /// How many independent tasks the auto-drain may run at once (each in its
    /// own git worktree). 1 = sequential (default).
    #[serde(default = "default_parallel")]
    pub max_parallel: usize,
    /// Auto-switch the OS input source to an ASCII layout on shortcut screens
    /// (and restore the IME for text input), so single-key shortcuts work
    /// while a CJK IME is on. macOS only; ignored elsewhere.
    #[serde(default = "default_true")]
    pub auto_ime: bool,
    /// Refuse to start runs while the planner's own ambiguity score is
    /// "high" — answer its questions (interview) or override. On by default.
    #[serde(default = "default_true")]
    pub ambiguity_gate: bool,
    /// Fold agent assets the repo already has (CLAUDE.md/AGENTS.md,
    /// .claude/skills, .cursor/rules, copilot-instructions) into the shared
    /// worker harness, worker-aware (docs/absorption.md A1). On by default.
    #[serde(default = "default_true")]
    pub harness_discovery: bool,
    /// Path to a local skill library (presets/skills layout: presets/*.skills +
    /// skills/<name>/SKILL.md). Empty = none. Read-only; equip links from it
    /// into .agents/skills/ (docs/skills.md S1).
    #[serde(default)]
    pub skill_library: String,
    /// Auto-equip core + detected-preset skills on plan/goal (I4: minimize
    /// intervention). Off = `yardlet skill suggest` nudges instead. On by default.
    #[serde(default = "default_true")]
    pub auto_equip: bool,
    /// Auto-record worker-proposed skills (a run's harness_suggestions of kind
    /// "skill") into `.agents/skills/` as `source: learned` (docs/skills.md
    /// S3). The deterministic core writes; the eval score later prunes weak
    /// ones. On by default (I4); off routes proposals to manual review.
    #[serde(default = "default_true")]
    pub auto_skill: bool,
    /// Auto-record worker-proposed rules (a run's harness_suggestions of kind
    /// "rule") as `.agents/rules/learned-<slug>.md`, an always-apply constraint
    /// H1 inlines into every packet (harness.md H4). OFF by default: rules are
    /// always-on (not per-task) and not auto-pruned, so one wrong learned rule
    /// degrades every later packet. Promote rules by hand instead. Reversible
    /// (git) and visible via `yardlet harness review`.
    #[serde(default)]
    pub auto_rule: bool,
    /// Auto-prune learned skills whose eval score stays below the floor over
    /// enough runs (the self-correction half of the loop, S4). Reversible
    /// (git keeps the file). On by default (I4); off = review surfaces them.
    #[serde(default = "default_true")]
    pub auto_prune: bool,
    /// Run workspace-owned hooks (`.agents/hooks/pre-run.d/*` before a worker
    /// spawns, `post-run.d/*` during evaluation; docs/harness.md H3). A
    /// non-zero pre-run hook blocks the run; a non-zero post-run hook blocks
    /// Done. On by default; the dirs are empty until you add executables.
    #[serde(default = "default_true")]
    pub hooks: bool,
}

fn default_access() -> String {
    "sandboxed".to_string()
}

fn default_parallel() -> usize {
    1
}

// ---------------------------------------------------------------------------
// .agents/intent-contract.yaml
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IntentContract {
    pub schema_version: u32,
    pub id: String,
    #[serde(default)]
    pub source: String,
    #[serde(default)]
    pub raw_request: String,
    #[serde(default)]
    pub summary: String,
    #[serde(default)]
    pub allowed_scope: Vec<String>,
    #[serde(default)]
    pub out_of_scope: Vec<String>,
    #[serde(default)]
    pub acceptance: Vec<yaml::Value>,
    /// Local image paths attached to this goal (passed to the worker natively:
    /// codex `-i`, claude reads them), so Yardlet does not lose the CLIs' vision.
    #[serde(default)]
    pub images: Vec<String>,
    /// The planner's own ambiguity self-report: low | medium | high.
    /// "high" gates the run until the interview lowers it (absorption.md A2).
    #[serde(default)]
    pub ambiguity: String,
    /// Questions the planner still has (shown by the interview gate).
    #[serde(default)]
    pub open_questions: Vec<String>,
    /// Interview Q->A pairs accumulated across re-plans.
    #[serde(default)]
    pub clarifications: Vec<String>,
    /// How many interview turns have run (hard cap applies).
    #[serde(default)]
    pub interview_turns: u32,
    #[serde(default)]
    pub status: String,
}

// ---------------------------------------------------------------------------
// .agents/work-queue.yaml
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkQueue {
    pub schema_version: u32,
    pub queue_id: String,
    #[serde(default)]
    pub intent_id: String,
    #[serde(default)]
    pub selection_policy: SelectionPolicy,
    #[serde(default)]
    pub tasks: Vec<Task>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SelectionPolicy {
    #[serde(default = "default_order")]
    pub default_order: String,
    #[serde(default)]
    pub require_planning_gate: bool,
    #[serde(default = "default_true")]
    pub skip_if_blocked: bool,
    #[serde(default = "default_true")]
    pub skip_if_approval_required: bool,
}

fn default_order() -> String {
    "priority_then_created_at".to_string()
}

impl Default for SelectionPolicy {
    fn default() -> Self {
        Self {
            default_order: default_order(),
            require_planning_gate: true,
            skip_if_blocked: true,
            skip_if_approval_required: true,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TaskState {
    #[default]
    Queued,
    Running,
    Done,
    Blocked,
    Failed,
    NeedsUser,
    /// Ran but did not fully complete — acceptance not met or a blocker found.
    Partial,
}

impl TaskState {
    pub fn glyph(self) -> &'static str {
        match self {
            TaskState::Done => "\u{2713}",    // check
            TaskState::Running => "\u{25b6}", // play
            TaskState::Blocked => "\u{2715}", // x
            TaskState::Failed => "!",
            TaskState::NeedsUser => "?",
            TaskState::Partial => "\u{25d0}", // half-filled circle
            TaskState::Queued => "\u{00b7}",  // middle dot
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Task {
    pub id: String,
    pub title: String,
    #[serde(default)]
    pub state: TaskState,
    #[serde(default)]
    pub priority: i64,
    #[serde(default)]
    pub risk: String,
    #[serde(default)]
    pub kind: String,
    #[serde(default)]
    pub preferred_worker: String,
    /// Optional per-task model override. Empty or "auto" = fall back to the
    /// worker profile's model, then the CLI's own default.
    #[serde(default)]
    pub model: String,
    /// Optional per-task reasoning effort. Empty or "auto" = worker default.
    /// codex: minimal|low|medium|high.
    #[serde(default)]
    pub effort: String,
    /// Task ids that must be Done before this task may run. Empty = independent
    /// (eligible to run in parallel with other independent tasks).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub depends_on: Vec<String>,
    /// Workspace skills (`.agents/skills/<name>/`) the worker must read before
    /// starting this task. Planner-assigned from the catalog.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub skills: Vec<String>,
    /// Executable affordances this task requires (e.g. `image_generation`).
    /// Planner-assigned. Routing constrains the candidate AND fallback set to
    /// workers whose `capabilities` declare every entry here; if none qualify
    /// the run fails with a clear message rather than silently mis-routing.
    /// Replaces the old hardcoded image-keyword router (no magic keywords).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub required_capabilities: Vec<String>,
    #[serde(default)]
    pub allowed_scope: Vec<String>,
    #[serde(default)]
    pub acceptance: Vec<yaml::Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub validation: Option<yaml::Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub approval: Option<yaml::Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub interaction: Option<yaml::Value>,
    /// One-line reason the planner chose this task's preferred_worker.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub worker_rationale: Option<String>,
    /// How this task entered the queue. Empty = planner/express goal (the
    /// default). `worker-proposed` = ingested from a run's result.json
    /// `follow_up_tasks` (propose -> ingest). Kept visible so an enqueued
    /// follow-up is a tracked CANDIDATE, never a silent expansion of the
    /// current task.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub provenance: String,
}

impl Task {
    /// Does this task require an explicit approval before it may run?
    pub fn approval_required(&self) -> bool {
        match &self.approval {
            Some(yaml::Value::Mapping(m)) => m
                .get(yaml::Value::String("required".into()))
                .and_then(|v| v.as_bool())
                .unwrap_or(false),
            _ => false,
        }
    }
}

impl WorkQueue {
    /// Are all of `task`'s dependencies Done? A dependency id that does not
    /// exist in the queue is treated as met (a planner typo must not deadlock
    /// the queue forever).
    pub fn deps_met(&self, task: &Task) -> bool {
        task.depends_on.iter().all(|dep| {
            self.tasks
                .iter()
                .find(|t| &t.id == dep)
                .map(|t| t.state == TaskState::Done)
                .unwrap_or(true)
        })
    }

    /// Sort tasks for display so what needs attention is on top and finished
    /// work sinks to the bottom: group by state (running first, then the
    /// needs-attention states, then queued, then done), and within each group by
    /// ascending `priority` (the scheduler's `select_next` key), ties kept in
    /// insertion order. So the running task and the next-to-run queued task sit
    /// at the top instead of below a long completed history. Display-only: the
    /// on-disk queue keeps its insertion / positional-insert order untouched.
    pub fn sort_for_display(&mut self) {
        fn rank(s: &TaskState) -> u8 {
            match s {
                TaskState::Running => 0,
                TaskState::NeedsUser => 1,
                TaskState::Blocked => 2,
                TaskState::Failed => 3,
                TaskState::Partial => 4,
                TaskState::Queued => 5,
                TaskState::Done => 6,
            }
        }
        self.tasks.sort_by(|a, b| {
            rank(&a.state)
                .cmp(&rank(&b.state))
                .then(a.priority.cmp(&b.priority))
        });
    }
}

// ---------------------------------------------------------------------------
// .agents/workers.yaml
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkersFile {
    pub schema_version: u32,
    #[serde(default)]
    pub workers: Vec<WorkerProfile>,
    #[serde(default)]
    pub routing: Routing,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Routing {
    #[serde(default = "default_codex")]
    pub default_worker: String,
    #[serde(default)]
    pub fallback_order: Vec<String>,
    /// Human cost dial read by the planner: cheap | balanced | quality.
    #[serde(default = "default_cost_bias")]
    pub cost_bias: String,
    #[serde(default)]
    pub planning_gate: GateRoute,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct GateRoute {
    #[serde(default)]
    pub primary: String,
    #[serde(default)]
    pub fallback: String,
}

fn default_codex() -> String {
    "codex".to_string()
}

fn default_cost_bias() -> String {
    "balanced".to_string()
}

impl Default for Routing {
    fn default() -> Self {
        Self {
            default_worker: default_codex(),
            fallback_order: vec!["codex".to_string(), "claude-code".to_string()],
            cost_bias: default_cost_bias(),
            planning_gate: GateRoute::default(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkerProfile {
    pub id: String,
    /// A disabled worker is skipped by routing and planning (toggle from the
    /// Home workers panel). Default on.
    #[serde(default = "default_true")]
    pub enabled: bool,
    #[serde(default)]
    pub kind: String,
    #[serde(default)]
    pub role_strengths: Vec<String>,
    /// Executable affordances this worker provides (e.g. `image_generation`).
    /// User-owned in workers.yaml. Distinct from `best_for` (a soft planner
    /// rubric) and `skills` (harness docs a worker reads): routing treats a
    /// task's `required_capabilities` as a HARD, deterministic constraint and
    /// only considers workers that declare every required capability. Names are
    /// normalized (lowercase, snake_case) before matching.
    #[serde(default)]
    pub capabilities: Vec<String>,
    /// Task characteristics this worker is good at (planner rubric; policy).
    #[serde(default)]
    pub best_for: String,
    /// Task characteristics to steer AWAY from this worker (negative planner
    /// rubric; policy). Best when contrastive with other workers' `best_for`.
    #[serde(default)]
    pub not_for: String,
    /// Relative subscription cost pressure: low | high (planner rubric).
    #[serde(default)]
    pub cost_weight: String,
    /// Model to run this worker with (alias or full id). Empty = CLI default.
    #[serde(default)]
    pub model: String,
    /// Reasoning effort level (codex: minimal|low|medium|high; claude: per CLI).
    /// Empty = CLI default.
    #[serde(default)]
    pub effort: String,
    #[serde(default)]
    pub billing: Billing,
    pub invocation: Invocation,
    #[serde(default)]
    pub limits: Limits,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Billing {
    #[serde(default)]
    pub mode: String,
}

impl Default for Billing {
    fn default() -> Self {
        Self {
            mode: "subscription_backed_only".to_string(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Invocation {
    pub command: String,
    #[serde(default)]
    pub supports_noninteractive: bool,
    #[serde(default)]
    pub output_contract: String,
    /// Generic adapter template for workers without a built-in adapter
    /// (codex and claude-code have first-class ones; any other id uses these).
    /// Placeholders: `{run_dir}`, `{model}`, `{effort}`, `{image}`. The task
    /// packet always arrives on stdin; the binary must support `--version`
    /// (the readiness probe) and be able to write files in the workspace.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub args: Vec<String>,
    /// Appended when running sandboxed (the default access level).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub sandbox_args: Vec<String>,
    /// Appended instead of `sandbox_args` when full access was granted.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub full_access_args: Vec<String>,
    /// Appended once per attached image, e.g. ["-i", "{image}"].
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub image_args: Vec<String>,
    /// Appended when a model is set, e.g. ["--model", "{model}"].
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub model_args: Vec<String>,
    /// Appended when an effort is set, e.g. ["--effort", "{effort}"].
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub effort_args: Vec<String>,
    /// Env vars passed through to THIS worker even when the billing policy
    /// scrubs them (e.g. ["OPENAI_API_KEY"] for an API-backed worker CLI).
    /// Explicit per-worker opt-in; zero-key remains the default and Yardlet
    /// itself never reads or stores the values.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub pass_env: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Limits {
    #[serde(default = "default_wall")]
    pub max_wall_minutes: u32,
    #[serde(default)]
    pub max_retries: u32,
}

fn default_wall() -> u32 {
    45
}

impl Default for Limits {
    fn default() -> Self {
        Self {
            max_wall_minutes: default_wall(),
            max_retries: 0,
        }
    }
}

// ---------------------------------------------------------------------------
// .agents/billing-policy.yaml
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct BillingPolicy {
    pub schema_version: u32,
    #[serde(default)]
    pub mode: String,
    #[serde(default)]
    pub worker_invocation: WorkerInvocationBilling,
    #[serde(default)]
    pub blocked_worker_env_names: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkerInvocationBilling {
    #[serde(default = "default_env_policy")]
    pub ai_billing_env_policy: String,
    #[serde(default = "default_true")]
    pub never_print_secret_values: bool,
    #[serde(default = "default_stop")]
    pub if_no_worker_ready: String,
    #[serde(default = "default_stop")]
    pub if_auth_ambiguous: String,
}

fn default_env_policy() -> String {
    "scrub_or_block".to_string()
}

fn default_stop() -> String {
    "stop".to_string()
}

impl Default for WorkerInvocationBilling {
    fn default() -> Self {
        Self {
            ai_billing_env_policy: default_env_policy(),
            never_print_secret_values: true,
            if_no_worker_ready: default_stop(),
            if_auth_ambiguous: default_stop(),
        }
    }
}

// ---------------------------------------------------------------------------
// Per-run result.json (written by the worker contract)
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunResult {
    pub schema_version: u32,
    pub run_id: String,
    pub task_id: String,
    pub status: String,
    #[serde(default)]
    pub intent_adherence: IntentAdherence,
    #[serde(default)]
    pub changes: Changes,
    #[serde(default)]
    pub validation: ValidationResult,
    #[serde(default)]
    pub question_for_user: Option<String>,
    #[serde(default)]
    pub compact_summary: String,
    /// Per-criterion verdict from a review/verify task — the structured
    /// quality signal Yardlet records instead of trusting prose (docs/skills.md).
    /// Empty for build tasks; populated by reviewer-role runs.
    #[serde(default)]
    pub verdict: Vec<Verdict>,
    /// Reusable lessons this run proposes (harness learning loop, H4). Yardlet
    /// records them; the worker never writes canonical state itself.
    #[serde(default)]
    pub harness_suggestions: Vec<HarnessSuggestion>,
    /// Follow-up tasks this run PROPOSES for the queue (propose -> ingest). The
    /// worker authors intent here instead of editing `.agents/work-queue.yaml`;
    /// Yardlet assigns ids/priority and is the sole writer of the queue.
    #[serde(default)]
    pub follow_up_tasks: Vec<FollowUpTask>,
}

/// A follow-up task a worker PROPOSES in its result (propose -> ingest). A
/// strict subset of the planner `PlanTask`: the worker authors intent; Yardlet
/// assigns `id`, `state`, and `priority` and stays the sole writer of the
/// queue. `reason` is the audit trail (why this follow-up exists). Every field
/// defaults so a malformed entry never crashes the whole result parse — empty
/// `title` entries are dropped at ingestion.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct FollowUpTask {
    #[serde(default)]
    pub title: String,
    #[serde(default)]
    pub reason: String,
    #[serde(default)]
    pub kind: String,
    #[serde(default)]
    pub risk: String,
    #[serde(default)]
    pub allowed_scope: Vec<String>,
    #[serde(default)]
    pub acceptance: Vec<String>,
    #[serde(default)]
    pub skills: Vec<String>,
    #[serde(default)]
    pub depends_on: Vec<String>,
    #[serde(default)]
    pub preferred_worker: String,
    #[serde(default)]
    pub required_capabilities: Vec<String>,
    #[serde(default)]
    pub worker_rationale: Option<String>,
    /// Where to place this task. `"next"` = run before the tasks already
    /// waiting (a priority nudge, soft ordering). `""` / `"end"` (default) =
    /// append after them. For a HARD "run before X" guarantee use `runs_before`.
    #[serde(default)]
    pub insert: String,
    /// Ids of existing queued tasks that must WAIT for this new one: Yardlet
    /// injects a dependency so each named task depends on this task (true
    /// "insert between"). Self-references, unknown ids, and entries that would
    /// form a dependency cycle are dropped.
    #[serde(default)]
    pub runs_before: Vec<String>,
}

// ---------------------------------------------------------------------------
// .agents/conversations/<task_id>.yaml — needs_user conversation transcript
// ---------------------------------------------------------------------------

/// Who authored a conversation turn on a task paused for the user.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TurnRole {
    /// The worker's user-facing message (its `question_for_user`).
    Worker,
    /// The user's reply (a clarifying question or the actual decision).
    User,
}

/// One turn in a task's `needs_user` conversation. Yardlet is the sole writer:
/// the worker authors its message via `question_for_user`, the user replies via
/// `yardlet answer`, and the core records both here.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConversationTurn {
    pub role: TurnRole,
    pub text: String,
    /// The run that produced a worker turn; empty for user turns. Used to
    /// dedupe so a retried run does not double-record the same message.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub run_id: String,
    /// RFC3339 timestamp the turn was recorded.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub ts: String,
}

/// The append-only transcript of a task's conversation with the user. Persisted
/// per task so a resume can thread the whole exchange back to the worker
/// (conversational memory), not just the last question.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Conversation {
    #[serde(default)]
    pub task_id: String,
    #[serde(default)]
    pub turns: Vec<ConversationTurn>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Verdict {
    /// The acceptance-criterion id being judged (e.g. "AC-004").
    #[serde(default)]
    pub criterion_id: String,
    pub pass: bool,
    /// Evidence for the verdict — a path, a line, a screenshot ref.
    #[serde(default)]
    pub evidence: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HarnessSuggestion {
    /// "rule" | "skill".
    #[serde(default)]
    pub kind: String,
    #[serde(default)]
    pub title: String,
    #[serde(default)]
    pub content: String,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct IntentAdherence {
    #[serde(default)]
    pub drift_detected: bool,
    #[serde(default)]
    pub notes: String,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Changes {
    #[serde(default)]
    pub files_modified: Vec<String>,
    #[serde(default)]
    pub files_created: Vec<String>,
    #[serde(default)]
    pub files_deleted: Vec<String>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ValidationResult {
    #[serde(default)]
    pub commands_run: Vec<String>,
    #[serde(default)]
    pub passed: bool,
    #[serde(default)]
    pub failures: Vec<String>,
}

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

    #[test]
    fn parses_seed_style_queue() {
        let src = r#"
schema_version: 1
queue_id: q
tasks:
  - id: YARD-001
    title: first
    state: queued
    priority: 10
    preferred_worker: codex
    acceptance:
      - one
  - id: YARD-002
    title: second
    state: done
    approval:
      required: true
"#;
        let q: WorkQueue = yaml::from_str(src).unwrap();
        assert_eq!(q.tasks.len(), 2);
        assert_eq!(q.tasks[0].state, TaskState::Queued);
        assert_eq!(q.tasks[1].state, TaskState::Done);
        assert!(!q.tasks[0].approval_required());
        assert!(q.tasks[1].approval_required());
        // selection_policy defaults applied when absent
        assert!(q.selection_policy.skip_if_approval_required);
    }

    #[test]
    fn task_state_snake_case_roundtrip() {
        let t: TaskState = yaml::from_str("needs_user").unwrap();
        assert_eq!(t, TaskState::NeedsUser);
        assert_eq!(yaml::to_string(&t).unwrap().trim(), "needs_user");
    }

    #[test]
    fn missing_optional_fields_default() {
        let t: Task = yaml::from_str("id: X\ntitle: T").unwrap();
        assert_eq!(t.state, TaskState::Queued); // #[default]
        assert_eq!(t.priority, 0);
        assert!(t.preferred_worker.is_empty());
        assert!(t.provenance.is_empty());
    }

    // A worker proposes follow-ups in result.json; parsing must be tolerant
    // (every FollowUpTask field defaults), so a minimal entry, a rich one, and
    // a malformed one missing its title all deserialize.
    #[test]
    fn follow_up_tasks_parse_tolerantly() {
        let src = r#"{
            "schema_version": 1,
            "run_id": "run-x",
            "task_id": "YARD-001",
            "status": "done",
            "follow_up_tasks": [
                { "title": "add tests", "reason": "coverage gap" },
                { "title": "refactor parser", "reason": "duplication",
                  "kind": "implementation", "risk": "low",
                  "acceptance": ["no dupes"], "depends_on": ["YARD-001"] },
                { "reason": "no title, should still parse" }
            ]
        }"#;
        let r: RunResult = serde_json::from_str(src).unwrap();
        assert_eq!(r.follow_up_tasks.len(), 3);
        assert_eq!(r.follow_up_tasks[0].title, "add tests");
        assert_eq!(r.follow_up_tasks[0].reason, "coverage gap");
        assert_eq!(
            r.follow_up_tasks[1].depends_on,
            vec!["YARD-001".to_string()]
        );
        assert!(r.follow_up_tasks[2].title.is_empty());
    }

    // A result.json with no follow_up_tasks field at all still parses (the
    // field defaults to empty) — back-compat with pre-0.6.2 workers.
    #[test]
    fn result_without_follow_up_tasks_defaults_empty() {
        let r: RunResult = serde_json::from_str(
            r#"{ "schema_version": 1, "run_id": "r", "task_id": "t", "status": "done" }"#,
        )
        .unwrap();
        assert!(r.follow_up_tasks.is_empty());
    }
}