vik 0.1.2

Vik is an issue-driven coding workflow automation tool.
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
//! `issues:` and `issue:` sections of the Workflow Definition.
//!
//! Two separate top-level keys map to two separate concerns. `issues`
//! (plural) holds the intake pull command. `issue` (singular) holds
//! per-issue handling: hooks and the named stages the orchestrator
//! dispatches against `issue.state`. Splitting them keeps intake config
//! editable without touching the stage map.

use std::path::PathBuf;

use indexmap::IndexMap;
use serde::de;
use serde::{Deserialize, Deserializer, Serialize};

use super::WorkflowSchema;
use super::diagnose::*;

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct IssueIntakeSchema {
  pub pull: IssuePullSchema,

  #[serde(flatten)]
  unknown_fields: serde_yaml::Mapping,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IssuePullSchema {
  pub command: String,

  #[serde(default = "default_idle_sec")]
  pub idle_sec: u64,

  #[serde(flatten)]
  unknown_fields: serde_yaml::Mapping,
}

fn default_idle_sec() -> u64 {
  5
}

impl Default for IssuePullSchema {
  fn default() -> Self {
    Self {
      command: String::new(),
      idle_sec: default_idle_sec(),
      unknown_fields: serde_yaml::Mapping::new(),
    }
  }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct IssueHandlingSchema {
  /// Cross-cutting hooks; run for every matched issue regardless of which
  /// stages fire. `after_create` is the only kind today.
  #[serde(default)]
  pub hooks: IssueHooks,

  /// Authored YAML stays a name-keyed map. Runtime storage keeps that ordered
  /// map and duplicates each map key into the stage value.
  #[serde(deserialize_with = "deserialize_stages")]
  pub stages: IndexMap<String, IssueStageSchema>,

  #[serde(flatten)]
  unknown_fields: serde_yaml::Mapping,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct IssueHooks {
  /// Runs once after the issue workdir is created and before any stage
  /// session spawns. Must be idempotent: every matched intake cycle reruns
  /// it because Vik keeps no per-issue marker file.
  pub after_create: Option<String>,

  #[serde(flatten)]
  unknown_fields: serde_yaml::Mapping,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IssueStageSchema {
  /// Derived from the `issue.stages.<name>` map key. `name` is not a
  /// supported field inside a stage body; if authored there, it remains an
  /// unknown-field diagnostic.
  #[serde(skip)]
  pub name: String,
  pub when: IssueStageMatch,
  pub agent: String,
  #[serde(flatten, deserialize_with = "deserialize_prompt_source")]
  pub prompt_source: IssueStagePromptSource,
  #[serde(default)]
  pub hooks: IssueStageHooks,

  #[serde(flatten)]
  unknown_fields: serde_yaml::Mapping,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum IssueStagePromptSource {
  #[serde(rename = "prompt_file")]
  File(PathBuf),
  #[serde(rename = "prompt")]
  Inline(String),
}

#[derive(Deserialize)]
struct IssueStagePromptSourceInput {
  #[serde(default)]
  prompt_file: Option<PathBuf>,
  #[serde(default)]
  prompt: Option<String>,
}

fn deserialize_prompt_source<'de, D>(deserializer: D) -> Result<IssueStagePromptSource, D::Error>
where
  D: Deserializer<'de>,
{
  let input = IssueStagePromptSourceInput::deserialize(deserializer)?;
  match (input.prompt_file, input.prompt) {
    (Some(prompt_file), None) => Ok(IssueStagePromptSource::File(prompt_file)),
    (None, Some(prompt)) => Ok(IssueStagePromptSource::Inline(prompt)),
    (Some(_), Some(_)) | (None, None) => Err(de::Error::custom(
      "issue stage must define exactly one of `prompt_file` or `prompt`",
    )),
  }
}

impl Default for IssueStagePromptSource {
  fn default() -> Self {
    Self::File(PathBuf::new())
  }
}

#[cfg(test)]
impl IssueStageSchema {
  pub fn new(when: impl Into<String>) -> Self {
    Self {
      name: String::new(),
      when: IssueStageMatch {
        state: when.into(),
        unknown_fields: Default::default(),
      },
      agent: String::new(),
      prompt_source: IssueStagePromptSource::default(),
      hooks: IssueStageHooks::default(),
      unknown_fields: Default::default(),
    }
  }

  pub fn with_name(mut self, name: impl Into<String>) -> Self {
    self.name = name.into();
    self
  }

  pub fn with_prompt_file(mut self, prompt_file: impl Into<PathBuf>) -> Self {
    self.prompt_source = IssueStagePromptSource::File(prompt_file.into());
    self
  }

  pub fn with_inline_prompt(mut self, prompt: impl Into<String>) -> Self {
    self.prompt_source = IssueStagePromptSource::Inline(prompt.into());
    self
  }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IssueStageMatch {
  /// Compared with case-sensitive equality to `issue.state`. Vik never
  /// normalizes tracker states; what the tracker reports is what matches.
  pub state: String,

  #[serde(flatten)]
  unknown_fields: serde_yaml::Mapping,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct IssueStageHooks {
  /// Failure aborts the stage before the session spawns.
  pub before_run: Option<String>,
  /// Skipped on cancellation; failure is logged but does not propagate.
  pub after_run: Option<String>,

  #[serde(flatten)]
  unknown_fields: serde_yaml::Mapping,
}

impl Diagnose for IssueIntakeSchema {
  fn diagnose(&self, schema: &WorkflowSchema) -> Diagnostics {
    let mut diagnostics = Diagnostics::new();

    diagnose_fields!(diagnostics, self, schema, "pull" => pull);
    diagnostics.warn_unknown_fields(&self.unknown_fields);

    diagnostics
  }
}

impl Diagnose for IssuePullSchema {
  fn diagnose(&self, _: &WorkflowSchema) -> Diagnostics {
    let mut diagnostics = Diagnostics::new();

    diagnostics.error_if_empty_str("command", &self.command);
    diagnostics.error_if_non_positive("idle_sec", self.idle_sec as usize);
    diagnostics.warn_unknown_fields(&self.unknown_fields);

    diagnostics
  }
}

impl Diagnose for IssueHandlingSchema {
  fn diagnose(&self, schema: &WorkflowSchema) -> Diagnostics {
    let mut diagnostics = Diagnostics::new();

    diagnostics.error_if_empty_map("stages", self.stages.is_empty());
    if !self.stages.is_empty() {
      self.stages.iter().for_each(|(name, stage)| {
        diagnostics.error_if_empty_str("stages", name);
        diagnostics.extends_with_pointer(&stage_pointer(name), stage.diagnose(schema));
      });
    }

    diagnose_fields!(diagnostics, self, schema, "hooks" => hooks);
    diagnostics.warn_unknown_fields(&self.unknown_fields);

    diagnostics
  }
}

fn deserialize_stages<'de, D>(deserializer: D) -> Result<IndexMap<String, IssueStageSchema>, D::Error>
where
  D: serde::Deserializer<'de>,
{
  let mut stages = IndexMap::<String, IssueStageSchema>::deserialize(deserializer)?;
  stages.iter_mut().for_each(|(name, stage)| {
    stage.name = name.clone();
  });

  Ok(stages)
}

fn stage_pointer(stage_name: &str) -> String {
  if stage_name.trim().is_empty() {
    "stages".to_string()
  } else {
    format!("stages.{stage_name}")
  }
}

impl Diagnose for IssueStageSchema {
  fn diagnose(&self, schema: &WorkflowSchema) -> Diagnostics {
    let mut diagnostics = Diagnostics::new();

    diagnose_fields!(
      diagnostics,
      self,
      schema,
      "when" => when,
      "hooks" => hooks,
    );
    diagnostics.error_if_empty_str("agent", &self.agent);

    // Stage's `agent` must reference an entry in the top-level `agents`
    // map; without this check, a typo would be caught only at session
    // spawn time, after intake and hooks have already run.
    if !self.agent.trim().is_empty() && !schema.agents.contains_key(&self.agent) {
      diagnostics.push(Diagnostic::error(
        "agent",
        DiagnosticCode::UnknownAgent(self.agent.clone()),
      ));
    }

    diagnostics.extends_with_pointer("", self.prompt_source.diagnose(schema));
    diagnostics.warn_unknown_fields(&self.unknown_fields);

    diagnostics
  }
}

impl Diagnose for IssueStagePromptSource {
  fn diagnose(&self, _: &WorkflowSchema) -> Diagnostics {
    let mut diagnostics = Diagnostics::new();

    match self {
      IssueStagePromptSource::File(prompt_file) => diagnostics.error_if_empty_path("prompt_file", prompt_file),
      IssueStagePromptSource::Inline(prompt) => diagnostics.error_if_empty_str("prompt", prompt),
    }

    diagnostics
  }
}

impl Diagnose for IssueHooks {
  fn diagnose(&self, _: &WorkflowSchema) -> Diagnostics {
    let mut diagnostics = Diagnostics::new();

    diagnostics.warn_unknown_fields(&self.unknown_fields);

    diagnostics
  }
}

impl Diagnose for IssueStageMatch {
  fn diagnose(&self, _: &WorkflowSchema) -> Diagnostics {
    let mut diagnostics = Diagnostics::new();

    diagnostics.error_if_empty_str("state", &self.state);
    diagnostics.warn_unknown_fields(&self.unknown_fields);

    diagnostics
  }
}

impl Diagnose for IssueStageHooks {
  fn diagnose(&self, _: &WorkflowSchema) -> Diagnostics {
    let mut diagnostics = Diagnostics::new();

    diagnostics.warn_unknown_fields(&self.unknown_fields);

    diagnostics
  }
}

#[cfg(test)]
mod tests {
  use crate::config::AgentProfileSchema;
  use crate::config::AgentRuntime;
  use crate::config::WorkflowSchema;
  use crate::config::diagnose::Diagnose;
  use crate::config::diagnose::DiagnosticCode;

  use super::*;

  #[test]
  fn issue_pull_defaults_idle_sec_when_omitted() {
    let pull: IssuePullSchema = serde_yaml::from_str(
      r#"
command: ./scripts/issues-json
"#,
    )
    .expect("pull schema parses");

    let diagnostics = pull.diagnose(&WorkflowSchema::default());

    assert_eq!(pull.command, "./scripts/issues-json");
    assert_eq!(pull.idle_sec, 5);
    assert!(!diagnostics.has_errors());
  }

  #[test]
  fn issue_stage_accepts_known_agent_and_reports_empty_prompt_file() {
    let mut workflow = WorkflowSchema::default();
    workflow.agents.insert(
      "codex".to_string(),
      AgentProfileSchema::new(AgentRuntime::Codex, "gpt-5.5".to_string()),
    );
    let stage: IssueStageSchema = serde_yaml::from_str(
      r#"
when:
  state: Todo
agent: codex
prompt_file: ''
"#,
    )
    .expect("stage schema parses");

    let diagnostics = stage.diagnose(&workflow);

    assert!(
      diagnostics
        .errors
        .iter()
        .any(|diag| { diag.pointer == "prompt_file" && matches!(diag.code, DiagnosticCode::EmptyStr) })
    );
    assert!(
      !diagnostics
        .errors
        .iter()
        .any(|diag| matches!(diag.code, DiagnosticCode::UnknownAgent(_)))
    );
  }

  #[test]
  fn issue_stages_deserialize_map_into_named_indexmap_entries() {
    let issue: IssueHandlingSchema = serde_yaml::from_str(
      r#"
stages:
  plan:
    when:
      state: todo
    agent: codex
    prompt_file: ./plan.md
  implement:
    when:
      state: todo
    agent: codex
    prompt_file: ./implement.md
"#,
    )
    .expect("issue schema parses");

    assert_eq!(
      issue.stages.keys().map(String::as_str).collect::<Vec<_>>(),
      ["plan", "implement"]
    );
    assert_eq!(issue.stages.get("plan").expect("plan stage").name, "plan");
    assert_eq!(
      issue.stages.get("implement").expect("implement stage").name,
      "implement"
    );
  }

  #[test]
  fn issue_stages_reject_array_shape() {
    let err = serde_yaml::from_str::<IssueHandlingSchema>(
      r#"
stages:
  - name: plan
    when:
      state: todo
    agent: codex
    prompt_file: ./plan.md
"#,
    )
    .expect_err("array-shaped stages are unsupported");

    assert!(err.to_string().contains("invalid type: sequence"));
  }

  #[test]
  fn issue_stages_report_empty_map() {
    let issue: IssueHandlingSchema = serde_yaml::from_str(
      r#"
stages: {}
"#,
    )
    .expect("issue schema parses");

    let diagnostics = issue.diagnose(&workflow_with_agent());

    assert!(
      diagnostics
        .errors
        .iter()
        .any(|diag| { diag.pointer == "stages" && matches!(diag.code, DiagnosticCode::EmptyMap) })
    );
  }

  #[test]
  fn issue_stages_report_empty_stage_name() {
    let issue: IssueHandlingSchema = serde_yaml::from_str(
      r#"
stages:
  "":
    when:
      state: todo
    agent: codex
    prompt_file: ./plan.md
"#,
    )
    .expect("issue schema parses");

    let diagnostics = issue.diagnose(&workflow_with_agent());

    assert!(
      diagnostics
        .errors
        .iter()
        .any(|diag| { diag.pointer == "stages" && matches!(diag.code, DiagnosticCode::EmptyStr) })
    );
  }

  #[test]
  fn issue_stages_derive_name_from_map_key_not_authored_field() {
    let issue: IssueHandlingSchema = serde_yaml::from_str(
      r#"
stages:
  plan:
    name: authored
    when:
      state: todo
    agent: codex
    prompt_file: ./plan.md
"#,
    )
    .expect("issue schema parses");

    let diagnostics = issue.diagnose(&workflow_with_agent());

    assert_eq!(issue.stages.get("plan").expect("plan stage").name, "plan");
    assert!(
      diagnostics
        .warnings
        .iter()
        .any(|diag| { diag.pointer == "stages.plan.name" && matches!(diag.code, DiagnosticCode::UnknownField) })
    );
  }

  #[test]
  fn issue_stage_prompt_source_accepts_prompt_file() {
    let stage: IssueStageSchema = serde_yaml::from_str(
      r#"
when:
  state: Todo
agent: codex
prompt_file: ./prompts/plan.md
"#,
    )
    .expect("stage schema parses");

    let IssueStagePromptSource::File(path) = stage.prompt_source else {
      panic!("expected file prompt source");
    };

    assert_eq!(path, PathBuf::from("./prompts/plan.md"));
  }

  #[test]
  fn issue_stage_prompt_source_accepts_inline_prompt() {
    let stage: IssueStageSchema = serde_yaml::from_str(
      r#"
when:
  state: Todo
agent: codex
prompt: |
  plan on {{ issue.id }}
"#,
    )
    .expect("stage schema parses");

    let diagnostics = stage.diagnose(&workflow_with_agent());

    assert!(!diagnostics.has_errors(), "{diagnostics}");
    assert!(!diagnostics.has_warnings(), "{diagnostics}");
  }

  #[test]
  fn issue_stage_prompt_source_rejects_both_sources() {
    let err = serde_yaml::from_str::<IssueStageSchema>(
      r#"
when:
  state: Todo
agent: codex
prompt_file: ./prompts/plan.md
prompt: inline
"#,
    )
    .expect_err("both prompt sources must fail");

    assert!(err.to_string().contains("prompt_file"));
    assert!(err.to_string().contains("prompt"));
  }

  #[test]
  fn issue_stage_prompt_source_rejects_missing_source() {
    let err = serde_yaml::from_str::<IssueStageSchema>(
      r#"
when:
  state: Todo
agent: codex
"#,
    )
    .expect_err("missing prompt source must fail");

    assert!(err.to_string().contains("prompt_file"));
    assert!(err.to_string().contains("prompt"));
  }

  #[test]
  fn issue_stage_prompt_source_preserves_unknown_field_warning() {
    let stage: IssueStageSchema = serde_yaml::from_str(
      r#"
when:
  state: Todo
agent: codex
prompt: inline
extra_stage_field: true
"#,
    )
    .expect("stage schema parses");

    let diagnostics = stage.diagnose(&workflow_with_agent());

    assert!(!diagnostics.has_errors(), "{diagnostics}");
    assert!(
      diagnostics
        .warnings
        .iter()
        .any(|diag| { diag.pointer == "extra_stage_field" && matches!(diag.code, DiagnosticCode::UnknownField) })
    );
  }

  fn workflow_with_agent() -> WorkflowSchema {
    let mut workflow = WorkflowSchema::default();
    workflow.agents.insert(
      "codex".to_string(),
      AgentProfileSchema::new(AgentRuntime::Codex, "gpt-5.5".to_string()),
    );
    workflow
  }
}