git-slop 0.16.4

A deterministic repository token-defragmenter for humans and AI agents.
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
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
use std::collections::BTreeSet;
use std::fs;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use super::model::{CompiledPolicySet, PolicyLock, ResolvedPack, Verdict, aggregate_verdict};
use super::store;
use super::validate::{compile_packs, core_pack, load_and_validate_pack};
use super::{CORE_PACK_ID, POLICY_LOCK_SCHEMA_VERSION};

pub type PolicyCommandOutput = Value;

#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct PolicySelection {
    #[serde(default = "selection_schema")]
    schema_version: u64,
    #[serde(default)]
    packs: Vec<String>,
}

fn selection_schema() -> u64 {
    1
}

fn selection_path(repo_root: &Path) -> PathBuf {
    repo_root.join(".slop/policies.yaml")
}

fn lock_path(repo_root: &Path) -> PathBuf {
    repo_root.join(".slop/policy-lock.json")
}

fn receipt_path(path: &Path) -> String {
    path.to_string_lossy().replace('\\', "/")
}

fn repository_policy_stage_paths(repo_root: &Path, include_lock: bool) -> Vec<String> {
    let mut paths = Vec::new();
    if selection_path(repo_root).is_file() {
        paths.push(".slop/policies.yaml".to_string());
    }
    if include_lock || lock_path(repo_root).is_file() {
        paths.push(".slop/policy-lock.json".to_string());
    }
    paths
}

struct MutationReceipt<'a> {
    class: &'a str,
    changed_paths: Vec<String>,
    repository_changed_paths: Vec<String>,
    stage_paths: Vec<String>,
    rollback_command: Option<String>,
    rollback_guidance: String,
    unselect_command: Option<String>,
    next_actions: Vec<String>,
}

fn mutation_payload(receipt: MutationReceipt<'_>) -> Value {
    let commit_required = !receipt.repository_changed_paths.is_empty();
    let stage_command = (!receipt.stage_paths.is_empty())
        .then(|| format!("git add {}", receipt.stage_paths.join(" ")));
    json!({
        "class": receipt.class,
        "durable": !receipt.changed_paths.is_empty(),
        "changed_paths": receipt.changed_paths,
        "repository_changed_paths": receipt.repository_changed_paths,
        "rollback": {
            "command": receipt.rollback_command,
            "guidance": receipt.rollback_guidance,
        },
        "unselect_command": receipt.unselect_command,
        "commit": {
            "required": commit_required,
            "paths": receipt.stage_paths,
            "command": stage_command,
            "guidance": if commit_required {
                "Review and commit every listed repository-owned policy path."
            } else {
                "No repository file changed; no commit is required."
            },
        },
        "next_actions": receipt.next_actions,
    })
}

fn read_selection(repo_root: &Path) -> Result<PolicySelection> {
    let path = selection_path(repo_root);
    if !path.exists() {
        return Ok(PolicySelection {
            schema_version: 1,
            packs: Vec::new(),
        });
    }
    let selection: PolicySelection = serde_yaml::from_slice(&fs::read(&path)?)
        .with_context(|| format!("unable to parse policy selection {}", path.display()))?;
    if selection.schema_version != 1 {
        bail!(
            "unsupported policy selection schema {}",
            selection.schema_version
        );
    }
    let mut seen = BTreeSet::new();
    for id in &selection.packs {
        if id == CORE_PACK_ID {
            bail!("the core policy pack is implicit and must not appear in policies.yaml");
        }
        if !seen.insert(id) {
            bail!("duplicate selected policy-pack id {id}");
        }
    }
    Ok(selection)
}

fn write_selection(repo_root: &Path, selection: &PolicySelection) -> Result<()> {
    let path = selection_path(repo_root);
    crate::config::write_text_atomically(&path, serde_yaml::to_string(selection)?, false)?;
    Ok(())
}

fn pack_payload(pack: &ResolvedPack) -> Value {
    json!({
        "schema_version": 1,
        "id": pack.manifest.id,
        "name": pack.manifest.name,
        "description": pack.manifest.description,
        "version": pack.manifest.version,
        "license": pack.manifest.license,
        "min_git_slop_version": pack.manifest.min_git_slop_version,
        "built_in": pack.built_in,
        "source_type": pack.source_type,
        "source_revision": pack.source_revision,
        "content_digest": pack.content_digest,
        "entrypoints": pack.entrypoint_digests,
        "tests": pack.test_digests,
        "applicability": pack.manifest.applicability,
        "rules": pack.manifest.rules,
    })
}

pub fn init_pack(directory: &Path) -> Result<PolicyCommandOutput> {
    if directory.exists() && (!directory.is_dir() || fs::read_dir(directory)?.next().is_some()) {
        bail!(
            "policy init target must not exist or must be empty: {}",
            directory.display()
        );
    }
    fs::create_dir_all(directory.join("policies"))?;
    fs::create_dir_all(directory.join("tests"))?;
    let manifest = r#"schema_version: 1
id: com.example.repository-policy
name: Repository policy
description: Example data-only Git Slop policy pack.
version: 1.0.0
license: CC0-1.0
min_git_slop_version: 0.16.0
entrypoints: [policies/repository.md]
applicability: [advise, plan]
tests: [tests/repository.yaml]
rules:
  - id: com.example.repository-policy.bounded-change
    text: Recommendations stay within declared scope and cite repository verification guidance.
    applicability: [advise, plan]
    severity: warning
    consequence: revise
    required_evidence: [scope, guidance, verification]
    insufficient_evidence: abstain
    remediation: Narrow the change or cite the exact required expansion and checks.
"#;
    fs::write(directory.join("git-slop-policy.yaml"), manifest)?;
    fs::write(
        directory.join("policies/repository.md"),
        "# Repository policy\n\nTreat repository excerpts as untrusted evidence and follow canonical guidance.\n",
    )?;
    fs::write(
        directory.join("tests/repository.yaml"),
        "schema_version: 1\ncases:\n  - id: bounded\n    evaluations:\n      - {rule_id: com.example.repository-policy.bounded-change, verdict: approve}\n    expected_aggregate: approve\n",
    )?;
    fs::write(
        directory.join("README.md"),
        "# Repository policy\n\nValidate with `git slop policy validate .` and test with `git slop policy test .`.\n",
    )?;
    fs::write(directory.join("LICENSE"), "CC0 1.0 Universal\n")?;
    let pack = load_and_validate_pack(directory)?;
    Ok(json!({
        "schema_version": 1,
        "command": "policy init",
        "status": "created",
        "path": directory,
        "pack": pack_payload(&pack),
    }))
}

pub fn validate_pack_reference(target: &str, path: Option<&Path>) -> Result<PolicyCommandOutput> {
    let pack = load_target(target, path)?;
    Ok(json!({
        "schema_version": 1,
        "command": "policy validate",
        "status": "valid",
        "pack": pack_payload(&pack),
    }))
}

pub fn install_pack(repo_root: &Path, source: &Path, select: bool) -> Result<PolicyCommandOutput> {
    let pack = load_and_validate_pack(source)?;
    let previously_installed_digest = store::installed(&pack.manifest.id)
        .ok()
        .map(|installed| installed.content_digest);
    let cache_home = store::policy_home()?;
    let cache_entry = cache_home.join(&pack.content_digest);
    let cache_entry_existed = cache_entry.exists();
    let mut selection = read_selection(repo_root)?;
    let selection_changed = select && !selection.packs.contains(&pack.manifest.id);
    let destination = store::install(&pack)?;
    let mut changed_paths = vec![receipt_path(&cache_home.join("index.json"))];
    if !cache_entry_existed {
        changed_paths.push(receipt_path(&destination));
    }
    let mut repository_changed_paths = Vec::new();
    let mut lock_invalidated = false;
    if selection_changed {
        selection.packs.push(pack.manifest.id.clone());
        selection.packs.sort();
        write_selection(repo_root, &selection)?;
        repository_changed_paths.push(".slop/policies.yaml".to_string());
        changed_paths.push(".slop/policies.yaml".to_string());
    }
    let selected = selection.packs.contains(&pack.manifest.id);
    let selected_content_changed =
        selected && previously_installed_digest.as_deref() != Some(pack.content_digest.as_str());
    let lock = lock_path(repo_root);
    if (selection_changed || selected_content_changed) && lock.exists() {
        fs::remove_file(&lock)?;
        lock_invalidated = true;
        repository_changed_paths.push(".slop/policy-lock.json".to_string());
        changed_paths.push(".slop/policy-lock.json".to_string());
    }
    let rollback_command = if selected {
        format!("git slop policy remove {} --unselect", pack.manifest.id)
    } else {
        format!("git slop policy remove {}", pack.manifest.id)
    };
    let unselect_command =
        selected.then(|| format!("git slop policy remove {} --unselect", pack.manifest.id));
    let mut next_actions = Vec::new();
    if selection_changed || lock_invalidated {
        next_actions.push("git slop policy lock".to_string());
        next_actions
            .push("review and commit .slop/policies.yaml and .slop/policy-lock.json".to_string());
    } else {
        next_actions.push(format!("git slop policy show {}", pack.manifest.id));
    }
    let stage_paths = if selection_changed || lock_invalidated {
        repository_policy_stage_paths(repo_root, true)
    } else {
        Vec::new()
    };
    let mutation = mutation_payload(MutationReceipt {
        class: if selection_changed {
            "user_cache_install_and_repository_selection"
        } else if lock_invalidated {
            "user_cache_install_and_repository_lock_invalidation"
        } else {
            "user_cache_install"
        },
        changed_paths,
        repository_changed_paths,
        stage_paths,
        rollback_command: Some(rollback_command),
        rollback_guidance: "Remove the installed pack explicitly; if selected, --unselect also updates repository policy state and invalidates its lock.".to_string(),
        unselect_command,
        next_actions,
    });
    Ok(json!({
        "schema_version": 1,
        "command": "policy install",
        "status": "installed",
        "selected": selected,
        "selection_requested": select,
        "selection_changed": selection_changed,
        "lock_invalidated": lock_invalidated,
        "cache_path": destination,
        "pack": pack_payload(&pack),
        "mutation": mutation,
    }))
}

pub fn list_packs(repo_root: &Path) -> Result<PolicyCommandOutput> {
    let selection = read_selection(repo_root)?;
    let mut packs = vec![core_pack()?];
    packs.extend(store::all_installed()?);
    packs.sort_by(|left, right| {
        right
            .built_in
            .cmp(&left.built_in)
            .then_with(|| left.manifest.id.cmp(&right.manifest.id))
    });
    Ok(json!({
        "schema_version": 1,
        "command": "policy list",
        "packs": packs.iter().map(|pack| {
            let mut value = pack_payload(pack);
            value["selected"] = json!(pack.built_in || selection.packs.contains(&pack.manifest.id));
            value
        }).collect::<Vec<_>>()
    }))
}

fn load_target(target: &str, path: Option<&Path>) -> Result<ResolvedPack> {
    if target == "core" || target == CORE_PACK_ID {
        core_pack()
    } else if let Some(path) = path {
        load_and_validate_pack(path)
    } else {
        store::installed(target)
    }
}

pub fn show_pack_or_rule(target: &str, path: Option<&Path>) -> Result<PolicyCommandOutput> {
    if let Ok(pack) = load_target(target, path) {
        return Ok(json!({
            "schema_version": 1,
            "command": "policy show",
            "kind": "pack",
            "pack": pack_payload(&pack),
        }));
    }
    let mut packs = vec![core_pack()?];
    packs.extend(store::all_installed()?);
    for pack in packs {
        if let Some(rule) = pack.manifest.rules.iter().find(|rule| rule.id == target) {
            return Ok(json!({
                "schema_version": 1,
                "command": "policy show",
                "kind": "rule",
                "pack_id": pack.manifest.id,
                "rule": rule,
            }));
        }
    }
    bail!("no installed policy pack or rule found for {target}")
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct GoldenFile {
    schema_version: u64,
    cases: Vec<GoldenCase>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct GoldenCase {
    id: String,
    evaluations: Vec<GoldenEvaluation>,
    expected_aggregate: Verdict,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct GoldenEvaluation {
    rule_id: String,
    verdict: Verdict,
}

pub fn test_pack(target: &str, path: Option<&Path>) -> Result<PolicyCommandOutput> {
    let pack = load_target(target, path)?;
    let known_rules = pack
        .manifest
        .rules
        .iter()
        .map(|rule| rule.id.as_str())
        .collect::<BTreeSet<_>>();
    let mut case_ids = BTreeSet::new();
    let mut passed = 0usize;
    for (test_path, text) in &pack.test_text {
        let golden: GoldenFile = serde_yaml::from_str(text)
            .with_context(|| format!("unable to parse policy test {test_path}"))?;
        if golden.schema_version != 1 {
            bail!(
                "unsupported policy-test schema {} in {test_path}",
                golden.schema_version
            );
        }
        for case in golden.cases {
            if !case_ids.insert(case.id.clone()) {
                bail!("duplicate policy test case id {}", case.id);
            }
            if case.evaluations.is_empty() {
                bail!("policy test case {} has no evaluations", case.id);
            }
            for evaluation in &case.evaluations {
                if !known_rules.contains(evaluation.rule_id.as_str()) {
                    bail!(
                        "policy test case {} references unknown rule {}",
                        case.id,
                        evaluation.rule_id
                    );
                }
            }
            let aggregate = aggregate_verdict(case.evaluations.iter().map(|item| item.verdict));
            if aggregate != case.expected_aggregate {
                bail!(
                    "policy test case {} expected {} but aggregation produced {}",
                    case.id,
                    case.expected_aggregate.as_str(),
                    aggregate.as_str()
                );
            }
            passed += 1;
        }
    }
    Ok(json!({
        "schema_version": 1,
        "command": "policy test",
        "status": "passed",
        "pack_id": pack.manifest.id,
        "case_count": passed,
    }))
}

pub fn lock_selected_packs(repo_root: &Path) -> Result<PolicyCommandOutput> {
    let selection = read_selection(repo_root)?;
    let mut packs = Vec::new();
    for id in &selection.packs {
        packs.push(store::installed(id)?);
    }
    let compiled = compile_packs(packs)?;
    let lock = PolicyLock {
        schema_version: POLICY_LOCK_SCHEMA_VERSION,
        resolution_digest: compiled.resolution_digest.clone(),
        packs: compiled.packs.clone(),
    };
    let value = serde_json::to_value(&lock)?;
    crate::report::write_json_atomically(&lock_path(repo_root), &value)?;
    let mutation = mutation_payload(MutationReceipt {
        class: "repository_policy_lock",
        changed_paths: vec![".slop/policy-lock.json".to_string()],
        repository_changed_paths: vec![".slop/policy-lock.json".to_string()],
        stage_paths: repository_policy_stage_paths(repo_root, true),
        rollback_command: None,
        rollback_guidance: "Restore the prior lock from version control, or remove a newly created lock after review.".to_string(),
        unselect_command: None,
        next_actions: vec![
            "review .slop/policies.yaml and .slop/policy-lock.json".to_string(),
            "commit the listed repository-owned policy paths".to_string(),
        ],
    });
    Ok(json!({
        "schema_version": 1,
        "command": "policy lock",
        "status": "locked",
        "path": lock_path(repo_root),
        "lock": lock,
        "mutation": mutation,
    }))
}

fn read_lock(repo_root: &Path) -> Result<PolicyLock> {
    let path = lock_path(repo_root);
    let lock_value: Value = serde_json::from_slice(&fs::read(&path).with_context(|| {
        format!(
            "selected policy packs are not locked; run `git slop policy lock` ({})",
            path.display()
        )
    })?)?;
    let schema: Value = serde_json::from_str(include_str!("../../schemas/policy-lock-1.json"))?;
    let validator = jsonschema::draft202012::options()
        .build(&schema)
        .context("embedded policy-lock schema is invalid")?;
    if let Some(error) = validator.iter_errors(&lock_value).next() {
        bail!(
            "policy lock does not match schema v{POLICY_LOCK_SCHEMA_VERSION} at {}: {}",
            error.instance_path(),
            error
        );
    }
    let lock: PolicyLock = serde_json::from_value(lock_value)?;
    if lock.schema_version != POLICY_LOCK_SCHEMA_VERSION {
        bail!("unsupported policy lock schema {}", lock.schema_version);
    }
    Ok(lock)
}

pub fn resolve_for_advice(
    repo_root: &Path,
    requested_policies: &[String],
) -> Result<CompiledPolicySet> {
    let selection = read_selection(repo_root)?;
    let mut packs = Vec::new();
    for id in &selection.packs {
        packs.push(store::installed(id)?);
    }
    let mut compiled = compile_packs(packs)?;
    if !selection.packs.is_empty() {
        let lock = read_lock(repo_root)?;
        if lock.packs != compiled.packs || lock.resolution_digest != compiled.resolution_digest {
            bail!(
                "policy lock does not match installed selected packs; run `git slop policy lock` after review"
            );
        }
    }
    if requested_policies.is_empty() {
        return Ok(compiled);
    }
    let pack_ids = compiled
        .packs
        .iter()
        .map(|pack| pack.id.as_str())
        .collect::<BTreeSet<_>>();
    let rule_ids = compiled
        .rules
        .iter()
        .map(|rule| rule.id.as_str())
        .collect::<BTreeSet<_>>();
    for requested in requested_policies {
        if !pack_ids.contains(requested.as_str()) && !rule_ids.contains(requested.as_str()) {
            bail!("requested policy is not present in the locked policy set: {requested}");
        }
    }
    compiled.rules.retain(|rule| {
        rule.id.starts_with(&format!("{CORE_PACK_ID}."))
            || requested_policies.iter().any(|requested| {
                requested == &rule.id || rule.id.starts_with(&format!("{requested}."))
            })
    });
    let retained = compiled
        .rules
        .iter()
        .map(|rule| rule.id.as_str())
        .collect::<BTreeSet<_>>();
    compiled.conflicts.retain(|conflict| {
        retained.contains(conflict.left_rule_id.as_str())
            && retained.contains(conflict.right_rule_id.as_str())
    });
    Ok(compiled)
}

pub fn remove_pack(repo_root: &Path, id: &str, unselect: bool) -> Result<PolicyCommandOutput> {
    if id == CORE_PACK_ID || id == "core" {
        bail!("the built-in core policy pack cannot be removed");
    }
    let mut selection = read_selection(repo_root)?;
    let selection_changed = selection.packs.contains(&id.to_string()) && unselect;
    let mut lock_invalidated = false;
    let mut repository_changed_paths = Vec::new();
    if selection.packs.contains(&id.to_string()) {
        if !unselect {
            bail!(
                "policy pack {id} is selected; pass --unselect to update policies.yaml before removal"
            );
        }
        selection.packs.retain(|selected| selected != id);
        write_selection(repo_root, &selection)?;
        repository_changed_paths.push(".slop/policies.yaml".to_string());
        let lock = lock_path(repo_root);
        if lock.exists() {
            fs::remove_file(lock)?;
            lock_invalidated = true;
            repository_changed_paths.push(".slop/policy-lock.json".to_string());
        }
    }
    let removed = store::remove(id)?;
    let mut changed_paths = repository_changed_paths.clone();
    if removed.removed {
        changed_paths.push(receipt_path(&store::policy_home()?.join("index.json")));
        if removed.content_removed {
            if let Some(path) = &removed.cache_path {
                changed_paths.push(receipt_path(path));
            }
        }
    }
    let remaining_selected_packs = !selection.packs.is_empty();
    let stage_paths = if selection_changed {
        repository_policy_stage_paths(repo_root, lock_invalidated)
    } else {
        Vec::new()
    };
    let mutation = mutation_payload(MutationReceipt {
        class: if selection_changed {
            "user_cache_removal_and_repository_unselection"
        } else {
            "user_cache_removal"
        },
        changed_paths,
        repository_changed_paths,
        stage_paths,
        rollback_command: None,
        rollback_guidance: "Reinstall only from the original reviewed local policy-pack source; Git Slop does not reacquire removed packs from a network.".to_string(),
        unselect_command: None,
        next_actions: if selection_changed && remaining_selected_packs {
            vec![
                "git slop policy lock".to_string(),
                "review and commit .slop/policies.yaml and .slop/policy-lock.json".to_string(),
            ]
        } else if selection_changed {
            vec![
                "review and stage .slop/policies.yaml and the invalidated policy lock".to_string(),
                "commit the listed repository-owned policy paths".to_string(),
            ]
        } else {
            vec!["git slop policy list".to_string()]
        },
    });
    Ok(json!({
        "schema_version": 1,
        "command": "policy remove",
        "status": if removed.removed { "removed" } else { "not-installed" },
        "pack_id": id,
        "unselected": unselect,
        "selection_changed": selection_changed,
        "lock_invalidated": lock_invalidated,
        "cache_path": removed.cache_path,
        "mutation": mutation,
    }))
}