govctl 0.8.0

Project governance CLI for RFC, ADR, and Work Item management
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
use serde::Deserialize;
use serde_json::Value;
use std::collections::HashSet;
use std::error::Error;
use std::fs;
use std::path::Path;

#[derive(Debug, Deserialize)]
struct EditOpsSpec {
    version: u32,
    aliases: Vec<AliasRule>,
    legacy_prefixes: Vec<LegacyPrefixRule>,
    simple_rules: Vec<SimpleFieldRule>,
    runtime_fields: Vec<RuntimeFieldRule>,
    nested_rules: Vec<NestedRootRule>,
    validation_rules: Vec<FieldValidationRule>,
}

#[derive(Debug, Deserialize)]
struct AliasRule {
    alias: String,
    canonical: String,
}

#[derive(Debug, Deserialize)]
struct LegacyPrefixRule {
    prefix: String,
    allowed_fields: Vec<String>,
}

#[derive(Debug, Deserialize)]
struct NestedRootRule {
    artifact: String,
    root: String,
    content_path: Vec<String>,
    node: NestedNodeRule,
}

#[derive(Debug, Deserialize)]
struct NestedFieldRule {
    name: String,
    node: NestedNodeRule,
}

#[derive(Debug, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum NestedNodeRule {
    Scalar {
        verbs: Vec<String>,
        set_mode: Option<RuntimeSetMode>,
    },
    Object {
        verbs: Vec<String>,
        fields: Vec<NestedFieldRule>,
    },
    List {
        verbs: Vec<String>,
        text_key: Option<String>,
        item: Box<NestedNodeRule>,
    },
}

#[derive(Debug, Deserialize)]
struct SimpleFieldRule {
    artifact: String,
    name: String,
    kind: String,
    verbs: Vec<String>,
}

#[derive(Debug, Deserialize)]
struct RuntimeFieldRule {
    artifact: String,
    name: String,
    get: Option<RuntimeGetRule>,
    set: Option<RuntimeSetRule>,
    list_path: Option<Vec<String>>,
}

#[derive(Debug, Deserialize)]
struct RuntimeGetRule {
    path: Vec<String>,
    render: String,
    status_key: Option<String>,
    text_key: Option<String>,
}

#[derive(Debug, Deserialize)]
struct RuntimeSetRule {
    path: Vec<String>,
    mode: RuntimeSetMode,
}

#[derive(Debug, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum RuntimeSetMode {
    String,
    Integer,
    OptionalString {
        empty_as_null: bool,
    },
    Enum {
        allowed: Vec<String>,
        invalid_msg: String,
        code: Option<String>,
    },
}

#[derive(Debug, Deserialize)]
struct FieldValidationRule {
    artifact: String,
    field: String,
    rule: String,
}

fn main() {
    // Recompile if any embedded .claude/ assets change
    // Skills
    println!("cargo:rerun-if-changed=.claude/skills/discuss/SKILL.md");
    println!("cargo:rerun-if-changed=.claude/skills/gov/SKILL.md");
    println!("cargo:rerun-if-changed=.claude/skills/quick/SKILL.md");
    println!("cargo:rerun-if-changed=.claude/skills/spec/SKILL.md");
    println!("cargo:rerun-if-changed=.claude/skills/rfc-writer/SKILL.md");
    println!("cargo:rerun-if-changed=.claude/skills/adr-writer/SKILL.md");
    println!("cargo:rerun-if-changed=.claude/skills/wi-writer/SKILL.md");
    println!("cargo:rerun-if-changed=.claude/skills/commit/SKILL.md");
    println!("cargo:rerun-if-changed=.claude/skills/migrate/SKILL.md");
    println!("cargo:rerun-if-changed=.claude/skills/decision-analysis/SKILL.md");
    // Agents
    println!("cargo:rerun-if-changed=.claude/agents/rfc-reviewer.md");
    println!("cargo:rerun-if-changed=.claude/agents/adr-reviewer.md");
    println!("cargo:rerun-if-changed=.claude/agents/wi-reviewer.md");
    println!("cargo:rerun-if-changed=.claude/agents/compliance-checker.md");

    // Edit rules SSOT + schema (ADR-0030)
    println!("cargo:rerun-if-changed=gov/schema/edit-ops.schema.json");
    println!("cargo:rerun-if-changed=gov/schema/edit-ops.json");

    generate_edit_rules().expect("failed to generate edit rules from SSOT");
}

fn generate_edit_rules() -> Result<(), Box<dyn Error>> {
    let spec_path = Path::new("gov/schema/edit-ops.json");
    let schema_path = Path::new("gov/schema/edit-ops.schema.json");
    let spec_text = fs::read_to_string(spec_path)?;
    let schema_text = fs::read_to_string(schema_path)?;
    let spec_value: Value = serde_json::from_str(&spec_text)?;
    let schema_value: Value = serde_json::from_str(&schema_text)?;

    validate_spec_against_schema(&schema_value, &spec_value)?;
    let spec: EditOpsSpec = serde_json::from_value(spec_value)?;
    validate_runtime_fields(&spec)?;
    let rendered = render_edit_rules(&spec)?;
    let rendered_runtime = render_edit_runtime(&spec)?;
    let out_dir = std::env::var("OUT_DIR")?;
    let out_path = Path::new(&out_dir).join("edit_rules_generated.rs");
    let out_runtime_path = Path::new(&out_dir).join("edit_runtime_generated.rs");
    fs::write(out_path, rendered)?;
    fs::write(out_runtime_path, rendered_runtime)?;
    Ok(())
}

fn validate_spec_against_schema(schema: &Value, instance: &Value) -> Result<(), Box<dyn Error>> {
    let compiled = jsonschema::validator_for(schema)
        .map_err(|err| format!("invalid edit-ops schema: {err}"))?;
    let mut diagnostics: Vec<String> = compiled
        .iter_errors(instance)
        .map(|err| err.to_string())
        .collect();
    if !diagnostics.is_empty() {
        diagnostics.sort();
        diagnostics.dedup();
        let body = diagnostics
            .into_iter()
            .map(|d| format!("  - {d}"))
            .collect::<Vec<_>>()
            .join("\n");
        return Err(format!("edit-ops.json failed schema validation:\n{body}").into());
    }
    Ok(())
}

fn validate_runtime_fields(spec: &EditOpsSpec) -> Result<(), Box<dyn Error>> {
    let mut seen = HashSet::new();
    for field in &spec.runtime_fields {
        let key = format!("{}:{}", field.artifact, field.name);
        if !seen.insert(key.clone()) {
            return Err(format!("duplicate runtime_fields entry in SSOT: {key}").into());
        }
        let simple = spec
            .simple_rules
            .iter()
            .find(|rule| rule.artifact == field.artifact && rule.name == field.name)
            .ok_or_else(|| format!("runtime_fields entry missing matching simple_rule: {}", key))?;

        if field.get.is_some() && !simple.verbs.iter().any(|v| v == "get") {
            return Err(format!(
                "runtime_fields {} defines get but simple_rules does not allow get",
                key
            )
            .into());
        }
        if field.set.is_some() && !simple.verbs.iter().any(|v| v == "set") {
            return Err(format!(
                "runtime_fields {} defines set but simple_rules does not allow set",
                key
            )
            .into());
        }
        if field.list_path.is_some() && !simple.verbs.iter().any(|v| v == "add" || v == "remove") {
            return Err(format!(
                "runtime_fields {} defines list_path but simple_rules has no add/remove verb",
                key
            )
            .into());
        }
    }
    Ok(())
}

fn render_edit_rules(spec: &EditOpsSpec) -> Result<String, Box<dyn Error>> {
    let mut out = String::new();
    out.push_str("// @generated by build.rs from gov/schema/edit-ops.json\n");
    out.push_str("// Do not edit manually.\n\n");
    out.push_str(&format!(
        "#[allow(dead_code)]\npub const EDIT_RULES_VERSION: u32 = {};\n\n",
        spec.version
    ));

    out.push_str("define_alias_resolver! {\n");
    for alias in &spec.aliases {
        out.push_str(&format!(
            "    ({:?}, {:?}),\n",
            alias.alias, alias.canonical
        ));
    }
    out.push_str("}\n\n");

    out.push_str("define_legacy_prefix_resolver! {\n");
    for rule in &spec.legacy_prefixes {
        out.push_str(&format!("    ({:?}, [", rule.prefix));
        for (idx, field) in rule.allowed_fields.iter().enumerate() {
            if idx > 0 {
                out.push_str(", ");
            }
            out.push_str(&format!("{field:?}"));
        }
        out.push_str("]),\n");
    }
    out.push_str("}\n\n");

    out.push_str("pub const SIMPLE_RULES: &[SimpleFieldRule] = &[\n");
    for field in &spec.simple_rules {
        let kind = match field.kind.as_str() {
            "scalar" => "Scalar",
            "list" => "List",
            other => return Err(format!("unknown simple field kind in SSOT: {other}").into()),
        };
        out.push_str("    SimpleFieldRule {\n");
        out.push_str(&format!("        artifact: {:?},\n", field.artifact));
        out.push_str(&format!("        name: {:?},\n", field.name));
        out.push_str(&format!("        kind: FieldKind::{kind},\n"));
        out.push_str("        verbs: &[\n");
        for verb in &field.verbs {
            out.push_str(&format!("            {verb:?},\n"));
        }
        out.push_str("        ],\n");
        out.push_str("    },\n");
    }
    out.push_str("];\n\n");

    let mut nested_defs = String::new();
    let mut nested_roots = String::new();
    for root in &spec.nested_rules {
        let const_name = format!(
            "NESTED_NODE_{}_{}_ROOT",
            root.artifact.to_uppercase(),
            sanitize_const_fragment(&root.root)
        );
        render_nested_node_defs(&mut nested_defs, &const_name, &root.node)?;
        nested_roots.push_str("    NestedRootRule {\n");
        nested_roots.push_str(&format!("        artifact: {:?},\n", root.artifact));
        nested_roots.push_str(&format!("        root: {:?},\n", root.root));
        nested_roots.push_str(&format!(
            "        content_path: {},\n",
            runtime_path_expr(&root.content_path)
        ));
        nested_roots.push_str(&format!("        node: &{},\n", const_name));
        nested_roots.push_str("    },\n");
    }

    out.push_str(&nested_defs);
    out.push_str("pub const NESTED_RULES: &[NestedRootRule] = &[\n");
    out.push_str(&nested_roots);
    out.push_str("];\n");

    out.push('\n');
    out.push_str("pub const VALIDATION_RULES: &[FieldValidationRule] = &[\n");
    for rule in &spec.validation_rules {
        let kind = match rule.rule.as_str() {
            "semver" => "Semver",
            "clause_superseded_by" => "ClauseSupersededBy",
            "artifact_ref" => "ArtifactRef",
            "enum_value" => "EnumValue",
            other => return Err(format!("unknown validation rule in SSOT: {other}").into()),
        };
        out.push_str("    FieldValidationRule {\n");
        out.push_str(&format!("        artifact: {:?},\n", rule.artifact));
        out.push_str(&format!("        field: {:?},\n", rule.field));
        out.push_str(&format!("        kind: ValidationKind::{kind},\n"));
        out.push_str("    },\n");
    }
    out.push_str("];\n");

    Ok(out)
}

fn sanitize_const_fragment(name: &str) -> String {
    name.chars()
        .map(|ch| {
            if ch.is_ascii_alphanumeric() {
                ch.to_ascii_uppercase()
            } else {
                '_'
            }
        })
        .collect()
}

fn render_nested_node_defs(
    out: &mut String,
    const_name: &str,
    node: &NestedNodeRule,
) -> Result<(), Box<dyn Error>> {
    match node {
        NestedNodeRule::Scalar { verbs, set_mode } => {
            out.push_str(&format!(
                "const {const_name}: NestedNodeRule = NestedNodeRule {{\n"
            ));
            out.push_str("    kind: NestedNodeKind::Scalar,\n");
            out.push_str(&format!("    verbs: {},\n", render_verbs_expr(verbs)));
            out.push_str("    text_key: None,\n");
            out.push_str(&format!(
                "    set_mode: {},\n",
                render_nested_scalar_mode_expr(set_mode.as_ref())?
            ));
            out.push_str("    item: None,\n");
            out.push_str("    fields: &[],\n");
            out.push_str("};\n\n");
        }
        NestedNodeRule::Object { verbs, fields } => {
            for field in fields {
                let child_const = format!("{const_name}_{}", sanitize_const_fragment(&field.name));
                render_nested_node_defs(out, &child_const, &field.node)?;
            }
            let fields_const = format!("{const_name}_FIELDS");
            out.push_str(&format!("const {fields_const}: &[NestedChildRule] = &[\n"));
            for field in fields {
                let child_const = format!("{const_name}_{}", sanitize_const_fragment(&field.name));
                out.push_str("    NestedChildRule {\n");
                out.push_str(&format!("        name: {:?},\n", field.name));
                out.push_str(&format!("        node: &{},\n", child_const));
                out.push_str("    },\n");
            }
            out.push_str("];\n");
            out.push_str(&format!(
                "const {const_name}: NestedNodeRule = NestedNodeRule {{\n"
            ));
            out.push_str("    kind: NestedNodeKind::Object,\n");
            out.push_str(&format!("    verbs: {},\n", render_verbs_expr(verbs)));
            out.push_str("    text_key: None,\n");
            out.push_str("    set_mode: None,\n");
            out.push_str("    item: None,\n");
            out.push_str(&format!("    fields: {},\n", fields_const));
            out.push_str("};\n\n");
        }
        NestedNodeRule::List {
            verbs,
            text_key,
            item,
        } => {
            let item_const = format!("{const_name}_ITEM");
            render_nested_node_defs(out, &item_const, item)?;
            out.push_str(&format!(
                "const {const_name}: NestedNodeRule = NestedNodeRule {{\n"
            ));
            out.push_str("    kind: NestedNodeKind::List,\n");
            out.push_str(&format!("    verbs: {},\n", render_verbs_expr(verbs)));
            out.push_str(&format!(
                "    text_key: {},\n",
                match text_key {
                    Some(key) => format!("Some({key:?})"),
                    None => "None".to_string(),
                }
            ));
            out.push_str("    set_mode: None,\n");
            out.push_str(&format!("    item: Some(&{}),\n", item_const));
            out.push_str("    fields: &[],\n");
            out.push_str("};\n\n");
        }
    }
    Ok(())
}

fn render_verbs_expr(verbs: &[String]) -> String {
    let mut out = String::from("&[");
    for (idx, verb) in verbs.iter().enumerate() {
        if idx > 0 {
            out.push_str(", ");
        }
        out.push_str(&format!("{verb:?}"));
    }
    out.push(']');
    out
}

fn render_nested_scalar_mode_expr(mode: Option<&RuntimeSetMode>) -> Result<String, Box<dyn Error>> {
    match mode {
        None => Ok("None".to_string()),
        Some(RuntimeSetMode::String) => Ok("Some(NestedScalarMode::String)".to_string()),
        Some(RuntimeSetMode::Integer) => Ok("Some(NestedScalarMode::Integer)".to_string()),
        Some(RuntimeSetMode::OptionalString { empty_as_null }) => Ok(format!(
            "Some(NestedScalarMode::OptionalString {{ empty_as_null: {} }})",
            empty_as_null
        )),
        Some(RuntimeSetMode::Enum {
            allowed,
            invalid_msg,
            code,
        }) => {
            let allowed_expr = {
                let mut expr = String::from("&[");
                for (idx, value) in allowed.iter().enumerate() {
                    if idx > 0 {
                        expr.push_str(", ");
                    }
                    expr.push_str(&format!("{value:?}"));
                }
                expr.push(']');
                expr
            };
            let code_expr = match code {
                Some(code) => format!("Some(DiagnosticCode::{})", diagnostic_code_variant(code)?),
                None => "None".to_string(),
            };
            Ok(format!(
                "Some(NestedScalarMode::Enum {{ allowed: {}, invalid_msg: {:?}, code: {} }})",
                allowed_expr, invalid_msg, code_expr
            ))
        }
    }
}

fn diagnostic_code_variant(code: &str) -> Result<&str, Box<dyn Error>> {
    code.strip_prefix('E')
        .map(|_| code)
        .ok_or_else(|| format!("invalid diagnostic code in SSOT: {code}").into())
}

fn render_edit_runtime(spec: &EditOpsSpec) -> Result<String, Box<dyn Error>> {
    let mut out = String::new();
    out.push_str("// @generated by build.rs from gov/schema/edit-ops.json\n");
    out.push_str("// Do not edit manually.\n\n");
    out.push_str("const RUNTIME_FIELDS: &[RuntimeFieldEntry] = &[\n");
    for field in &spec.runtime_fields {
        out.push_str("    RuntimeFieldEntry {\n");
        out.push_str(&format!(
            "        artifact: {},\n",
            runtime_artifact_expr(&field.artifact)?
        ));
        out.push_str(&format!("        field: {:?},\n", field.name));
        out.push_str(&format!(
            "        get: {},\n",
            runtime_get_expr(field.get.as_ref())?
        ));
        out.push_str(&format!(
            "        set: {},\n",
            runtime_set_expr(field.set.as_ref())?
        ));
        out.push_str(&format!(
            "        list_path: {},\n",
            runtime_list_path_expr(field.list_path.as_ref())
        ));
        out.push_str("    },\n");
    }
    out.push_str("];\n");
    Ok(out)
}

fn runtime_artifact_expr(artifact: &str) -> Result<&'static str, Box<dyn Error>> {
    match artifact {
        "rfc" => Ok("ArtifactType::Rfc"),
        "clause" => Ok("ArtifactType::Clause"),
        "adr" => Ok("ArtifactType::Adr"),
        "work" => Ok("ArtifactType::WorkItem"),
        "guard" => Ok("ArtifactType::Guard"),
        other => Err(format!("unknown runtime artifact in SSOT: {other}").into()),
    }
}

fn runtime_path_expr(path: &[String]) -> String {
    let mut out = String::from("&[");
    for (idx, seg) in path.iter().enumerate() {
        if idx > 0 {
            out.push_str(", ");
        }
        out.push_str(&format!("{seg:?}"));
    }
    out.push(']');
    out
}

fn runtime_list_path_expr(path: Option<&Vec<String>>) -> String {
    match path {
        Some(path) => format!("Some({})", runtime_path_expr(path)),
        None => "None".to_string(),
    }
}

fn runtime_get_expr(get: Option<&RuntimeGetRule>) -> Result<String, Box<dyn Error>> {
    let Some(get) = get else {
        return Ok("None".to_string());
    };
    let render = match get.render.as_str() {
        "scalar" => "RenderMode::Scalar".to_string(),
        "csv_strings" => "RenderMode::CsvStrings".to_string(),
        "line_strings" => "RenderMode::LineStrings".to_string(),
        "text_lines" => {
            let text_key = get.text_key.as_ref().ok_or_else(|| {
                "runtime get render=text_lines requires text_key in SSOT".to_string()
            })?;
            format!("RenderMode::TextLines {{ text_key: {:?} }}", text_key)
        }
        "status_lines" => {
            let status_key = get.status_key.as_ref().ok_or_else(|| {
                "runtime get render=status_lines requires status_key in SSOT".to_string()
            })?;
            let text_key = get.text_key.as_ref().ok_or_else(|| {
                "runtime get render=status_lines requires text_key in SSOT".to_string()
            })?;
            format!(
                "RenderMode::StatusLines {{ status_key: {:?}, text_key: {:?} }}",
                status_key, text_key
            )
        }
        other => return Err(format!("unknown runtime get render in SSOT: {other}").into()),
    };
    Ok(format!(
        "Some(SimpleFieldSpec {{ path: {}, render: {} }})",
        runtime_path_expr(&get.path),
        render
    ))
}

fn runtime_set_expr(set: Option<&RuntimeSetRule>) -> Result<String, Box<dyn Error>> {
    let Some(set) = set else {
        return Ok("None".to_string());
    };
    let mode = match &set.mode {
        RuntimeSetMode::String => "SetMode::String".to_string(),
        RuntimeSetMode::Integer => "SetMode::Integer".to_string(),
        RuntimeSetMode::OptionalString { empty_as_null } => format!(
            "SetMode::OptionalString {{ empty_as_null: {} }}",
            empty_as_null
        ),
        RuntimeSetMode::Enum {
            allowed,
            invalid_msg,
            code,
        } => {
            let allowed_expr = runtime_path_expr(allowed);
            let code_expr = match code {
                Some(code) => format!("Some(DiagnosticCode::{code})"),
                None => "None".to_string(),
            };
            format!(
                "SetMode::Enum {{ allowed: {}, invalid_msg: {:?}, code: {} }}",
                allowed_expr, invalid_msg, code_expr
            )
        }
    };
    Ok(format!(
        "Some(SimpleSetSpec {{ path: {}, mode: {} }})",
        runtime_path_expr(&set.path),
        mode
    ))
}