git-slop 0.16.0

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
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 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 destination = store::install(&pack)?;
    if select {
        let mut selection = read_selection(repo_root)?;
        if !selection.packs.contains(&pack.manifest.id) {
            selection.packs.push(pack.manifest.id.clone());
            selection.packs.sort();
            write_selection(repo_root, &selection)?;
        }
    }
    Ok(json!({
        "schema_version": 1,
        "command": "policy install",
        "status": "installed",
        "selected": select,
        "cache_path": destination,
        "pack": pack_payload(&pack),
    }))
}

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)?;
    Ok(json!({
        "schema_version": 1,
        "command": "policy lock",
        "status": "locked",
        "path": lock_path(repo_root),
        "lock": lock,
    }))
}

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)?;
    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)?;
        let lock = lock_path(repo_root);
        if lock.exists() {
            fs::remove_file(lock)?;
        }
    }
    let removed = store::remove(id)?;
    Ok(json!({
        "schema_version": 1,
        "command": "policy remove",
        "status": if removed { "removed" } else { "not-installed" },
        "pack_id": id,
        "unselected": unselect,
    }))
}