beads_rust 0.2.17

Agent-first issue tracker (SQLite + JSONL)
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
//! Regression coverage for the notify-ACFS workflow's local contract.

use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus};

use serde::Deserialize;
use serde_json::Value as JsonValue;
use serde_yml::Value as YamlValue;
use sha2::{Digest, Sha256};

const WORKFLOW_PATH: &str = ".github/workflows/notify-acfs.yml";
const INSTALLER_PATH: &str = "install.sh";
const HAS_TOKEN_OUTPUT: &str = "steps.check_token.outputs.has_token"; // ubs:ignore - GitHub Actions output name in a test assertion, not a secret value
const TRUE_COMPARISON: &str = " == ";
const TRUE_LITERAL: &str = "'true'";

#[derive(Debug, Deserialize)]
struct Workflow {
    jobs: BTreeMap<String, Job>,
}

#[derive(Debug, Deserialize)]
struct Job {
    steps: Vec<Step>,
}

#[derive(Debug, Deserialize)]
struct Step {
    name: Option<String>,
    run: Option<String>,
    uses: Option<String>,
    #[serde(rename = "if")]
    condition: Option<String>,
    with: Option<BTreeMap<String, YamlValue>>,
}

struct ShellOutput {
    status: ExitStatus,
    stdout: String,
    stderr: String,
}

#[test]
fn notify_workflow_exposes_expected_steps_and_main_trigger() -> Result<(), String> {
    let raw = read_to_string(Path::new(WORKFLOW_PATH))?;
    require_contains(&raw, "branches: [main]")?;
    let legacy_branch_trigger = format!("branches: [{}]", ["mas", "ter"].concat());
    require_not_contains(&raw, &legacy_branch_trigger)?;

    for step_name in [
        "Compute SHA256",
        "Get previous checksum",
        "Compare checksums",
        "Notify ACFS (dry run)",
        "Check for ACFS_NOTIFY_TOKEN",
        "Notify ACFS",
        "Summary",
    ] {
        workflow_step(step_name)?;
    }

    Ok(())
}

#[test]
fn checksum_fragment_records_current_installer_hash() -> Result<(), String> {
    let script = rendered_step_script(
        "Compute SHA256",
        &[("${{ env.INSTALLER_PATH }}", INSTALLER_PATH)],
    )?;
    let fixture = NotifyFixture::new()?;
    fixture.write_installer(b"current installer\n")?;
    let output_path = fixture.root().join("github-output");
    let output_path_text = path_string(&output_path);

    let result = run_bash_step(
        &script,
        fixture.root(),
        &[("GITHUB_OUTPUT", output_path_text.as_str())],
    )?;
    require_success(&result)?;
    let github_output = read_to_string(&output_path)?;
    require_contains(
        &github_output,
        &format!("sha256={}", sha256_hex(b"current installer\n")),
    )
}

#[test]
fn previous_checksum_fragment_handles_previous_and_missing_versions() -> Result<(), String> {
    let script = rendered_step_script(
        "Get previous checksum",
        &[("${{ env.INSTALLER_PATH }}", INSTALLER_PATH)],
    )?;

    let changed = NotifyFixture::new()?;
    changed.init_repo()?;
    changed.commit_installer("old", b"old installer\n")?;
    changed.commit_installer("new", b"new installer\n")?;
    let changed_output = changed.root().join("changed-output");
    let changed_output_text = path_string(&changed_output);
    let result = run_bash_step(
        &script,
        changed.root(),
        &[("GITHUB_OUTPUT", changed_output_text.as_str())],
    )?;
    require_success(&result)?;
    let github_output = read_to_string(&changed_output)?;
    require_contains(
        &github_output,
        &format!("prev_sha256={}", sha256_hex(b"old installer\n")),
    )?;

    let initial = NotifyFixture::new()?;
    initial.init_repo()?;
    initial.commit_installer("initial", b"first installer\n")?;
    let initial_output = initial.root().join("initial-output");
    let initial_output_text = path_string(&initial_output);
    let result = run_bash_step(
        &script,
        initial.root(),
        &[("GITHUB_OUTPUT", initial_output_text.as_str())],
    )?;
    require_success(&result)?;
    require_contains(&read_to_string(&initial_output)?, "prev_sha256=none")
}

#[test]
fn compare_fragment_reports_changed_and_unchanged_states() -> Result<(), String> {
    let changed_script = rendered_step_script(
        "Compare checksums",
        &[
            ("${{ steps.checksum.outputs.sha256 }}", "new"),
            ("${{ steps.previous.outputs.prev_sha256 }}", "old"),
        ],
    )?;
    let unchanged_script = rendered_step_script(
        "Compare checksums",
        &[
            ("${{ steps.checksum.outputs.sha256 }}", "same"),
            ("${{ steps.previous.outputs.prev_sha256 }}", "same"),
        ],
    )?;
    let fixture = NotifyFixture::new()?;
    let changed_output = fixture.root().join("changed");
    let unchanged_output = fixture.root().join("unchanged");
    let changed_output_text = path_string(&changed_output);
    let unchanged_output_text = path_string(&unchanged_output);

    require_success(&run_bash_step(
        &changed_script,
        fixture.root(),
        &[("GITHUB_OUTPUT", changed_output_text.as_str())],
    )?)?;
    require_success(&run_bash_step(
        &unchanged_script,
        fixture.root(),
        &[("GITHUB_OUTPUT", unchanged_output_text.as_str())],
    )?)?;
    require_contains(&read_to_string(&changed_output)?, "changed=true")?;
    require_contains(&read_to_string(&unchanged_output)?, "changed=false")
}

#[test]
fn dry_run_and_dispatch_conditions_cover_changed_force_and_token_paths() -> Result<(), String> {
    let dry_run = workflow_step("Notify ACFS (dry run)")?;
    let token = workflow_step("Check for ACFS_NOTIFY_TOKEN")?;
    let dispatch = workflow_step("Notify ACFS")?;

    let change_or_force =
        "(steps.compare.outputs.changed == 'true' || github.event.inputs.force == 'true')";
    require_contains(step_condition(&dry_run)?, change_or_force)?;
    require_contains(
        step_condition(&dry_run)?,
        "github.event.inputs.dry_run == 'true'",
    )?;
    require_contains(step_condition(&token)?, change_or_force)?;
    require_contains(
        step_condition(&token)?,
        "github.event.inputs.dry_run != 'true'",
    )?;
    require_contains(step_condition(&dispatch)?, change_or_force)?;
    require_contains(
        step_condition(&dispatch)?,
        "github.event.inputs.dry_run != 'true'",
    )?;
    let has_token_true = [HAS_TOKEN_OUTPUT, TRUE_COMPARISON, TRUE_LITERAL].concat();
    require_contains(step_condition(&dispatch)?, &has_token_true)
}

#[test]
fn dry_run_fragment_reports_intended_notification() -> Result<(), String> {
    let script = rendered_step_script(
        "Notify ACFS (dry run)",
        &[
            ("${{ env.TOOL_NAME }}", "br"),
            ("${{ steps.checksum.outputs.sha256 }}", "abc123"),
        ],
    )?;
    let fixture = NotifyFixture::new()?;

    let result = run_bash_step(&script, fixture.root(), &[])?;
    require_success(&result)?;
    require_contains(&result.stdout, "DRY RUN - Would send notification to ACFS")?;
    require_contains(&result.stdout, "Tool: br")?;
    require_contains(&result.stdout, "SHA256: abc123")
}

#[test]
fn missing_token_fragment_is_notice_not_failure() -> Result<(), String> {
    let script = workflow_step_script("Check for ACFS_NOTIFY_TOKEN")?;
    let fixture = NotifyFixture::new()?;
    let output_path = fixture.root().join("github-output");
    let output_path_text = path_string(&output_path);

    let result = run_bash_step(
        &script,
        fixture.root(),
        &[
            ("GITHUB_OUTPUT", output_path_text.as_str()),
            ("ACFS_NOTIFY_TOKEN", ""),
        ],
    )?;
    require_success(&result)?;
    require_contains(
        &result.stdout,
        "ACFS_NOTIFY_TOKEN is not configured; skipping notification.",
    )?;
    require_contains(&read_to_string(&output_path)?, "has_token=false")
}

#[test]
fn dispatch_payload_shape_is_secret_free_and_complete() -> Result<(), String> {
    let dispatch = workflow_step("Notify ACFS")?;
    let uses = dispatch
        .uses
        .as_deref()
        .ok_or_else(|| "Notify ACFS step must use repository-dispatch".to_owned())?;
    require_contains(uses, "peter-evans/repository-dispatch@")?;

    let with = dispatch
        .with
        .as_ref()
        .ok_or_else(|| "Notify ACFS step must have with block".to_owned())?;
    let repository = yaml_string(with, "repository")?;
    let event_type = yaml_string(with, "event-type")?;
    let payload = yaml_string(with, "client-payload")?;
    require_contains(repository, "${{ env.ACFS_REPO }}")?;
    require_contains(event_type, "installer-updated")?;

    let parsed: JsonValue = serde_json::from_str(payload)
        .map_err(|error| format!("client-payload must stay valid JSON: {error}\n{payload}"))?;
    require_json_string(&parsed, "tool", "${{ env.TOOL_NAME }}")?;
    require_json_string(
        &parsed,
        "new_sha256",
        "${{ steps.checksum.outputs.sha256 }}",
    )?;
    require_json_string(
        &parsed,
        "old_sha256",
        "${{ steps.previous.outputs.prev_sha256 }}",
    )?;
    require_json_string(&parsed, "repo", "${{ github.repository }}")?;
    require_json_string(&parsed, "commit", "${{ github.sha }}")?;
    require_not_contains(payload, "ACFS_NOTIFY_TOKEN")
}

#[test]
fn summary_fragment_records_workflow_outcome() -> Result<(), String> {
    let script = rendered_step_script(
        "Summary",
        &[
            ("${{ env.TOOL_NAME }}", "br"),
            ("${{ steps.checksum.outputs.sha256 }}", "abc123"),
            ("${{ steps.compare.outputs.changed }}", "true"),
        ],
    )?;
    let fixture = NotifyFixture::new()?;
    let summary_path = fixture.root().join("summary.md");
    let summary_path_text = path_string(&summary_path);

    let result = run_bash_step(
        &script,
        fixture.root(),
        &[("GITHUB_STEP_SUMMARY", summary_path_text.as_str())],
    )?;
    require_success(&result)?;
    let summary = read_to_string(&summary_path)?;
    require_contains(&summary, "## ACFS Notification Summary")?;
    require_contains(&summary, "| Tool | br |")?;
    require_contains(&summary, "| SHA256 | `abc123` |")?;
    require_contains(&summary, "| Changed | true |")
}

fn workflow_step(step_name: &str) -> Result<Step, String> {
    let raw = read_to_string(Path::new(WORKFLOW_PATH))?;
    let workflow: Workflow = serde_yml::from_str(&raw)
        .map_err(|error| format!("failed to parse {WORKFLOW_PATH}: {error}"))?;

    workflow
        .jobs
        .into_values()
        .flat_map(|job| job.steps)
        .find(|step| step.name.as_deref() == Some(step_name))
        .ok_or_else(|| format!("workflow step not found: {step_name}"))
}

fn workflow_step_script(step_name: &str) -> Result<String, String> {
    let step = workflow_step(step_name)?;
    step.run
        .ok_or_else(|| format!("workflow step {step_name:?} has no run script"))
}

fn rendered_step_script(step_name: &str, replacements: &[(&str, &str)]) -> Result<String, String> {
    let mut script = workflow_step_script(step_name)?;
    for (needle, replacement) in replacements {
        script = script.replace(needle, replacement);
    }
    require_not_contains(&script, "${{")?;
    Ok(script)
}

fn step_condition(step: &Step) -> Result<&str, String> {
    step.condition
        .as_deref()
        .ok_or_else(|| format!("step {:?} has no if condition", step.name))
}

fn yaml_string<'a>(values: &'a BTreeMap<String, YamlValue>, key: &str) -> Result<&'a str, String> {
    values
        .get(key)
        .and_then(YamlValue::as_str)
        .ok_or_else(|| format!("with block has no string value for {key:?}: {values:#?}"))
}

fn require_json_string(json: &JsonValue, key: &str, expected: &str) -> Result<(), String> {
    let actual = json
        .get(key)
        .and_then(JsonValue::as_str)
        .ok_or_else(|| format!("payload has no string {key:?}: {json}"))?;
    if actual == expected {
        Ok(())
    } else {
        Err(format!(
            "payload {key:?} mismatch: expected {expected:?}, got {actual:?}"
        ))
    }
}

fn run_bash_step(
    script: &str,
    working_dir: &Path,
    envs: &[(&str, &str)],
) -> Result<ShellOutput, String> {
    let mut command = Command::new("bash");
    command
        .arg("-euo")
        .arg("pipefail")
        .arg("-c")
        .arg(script)
        .current_dir(working_dir);
    for (key, value) in envs {
        command.env(key, value);
    }
    let output = command
        .output()
        .map_err(|error| format!("failed to run bash fragment: {error}"))?;

    Ok(ShellOutput {
        status: output.status,
        stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
        stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
    })
}

fn require_success(output: &ShellOutput) -> Result<(), String> {
    if output.status.success() {
        Ok(())
    } else {
        Err(format!(
            "fragment failed with status {:?}\nstdout:\n{}\nstderr:\n{}",
            output.status.code(),
            output.stdout,
            output.stderr
        ))
    }
}

fn require_contains(haystack: &str, needle: &str) -> Result<(), String> {
    if haystack.contains(needle) {
        Ok(())
    } else {
        Err(format!("expected to find {needle:?} in:\n{haystack}"))
    }
}

fn require_not_contains(haystack: &str, needle: &str) -> Result<(), String> {
    if haystack.contains(needle) {
        Err(format!("did not expect to find {needle:?} in:\n{haystack}"))
    } else {
        Ok(())
    }
}

fn read_to_string(path: &Path) -> Result<String, String> {
    fs::read_to_string(path).map_err(|error| format!("failed to read {}: {error}", path.display()))
}

fn path_string(path: &Path) -> String {
    path.to_string_lossy().into_owned()
}

fn sha256_hex(bytes: &[u8]) -> String {
    let digest = Sha256::digest(bytes);
    let mut encoded = String::with_capacity(64);
    for byte in digest {
        use std::fmt::Write as _;
        let _ = write!(&mut encoded, "{byte:02x}");
    }
    encoded
}

struct NotifyFixture {
    temp_dir: tempfile::TempDir,
}

impl NotifyFixture {
    fn new() -> Result<Self, String> {
        Ok(Self {
            temp_dir: tempfile::TempDir::new()
                .map_err(|error| format!("failed to create temp fixture: {error}"))?,
        })
    }

    fn root(&self) -> &Path {
        self.temp_dir.path()
    }

    fn installer_path(&self) -> PathBuf {
        self.root().join(INSTALLER_PATH)
    }

    fn write_installer(&self, bytes: &[u8]) -> Result<(), String> {
        fs::write(self.installer_path(), bytes)
            .map_err(|error| format!("failed to write installer fixture: {error}"))
    }

    fn init_repo(&self) -> Result<(), String> {
        run_git(self.root(), &["init", "-q"])?;
        run_git(
            self.root(),
            &["config", "user.email", "test@example.invalid"],
        )?;
        run_git(
            self.root(),
            &["config", "user.name", "Workflow Notify Test"],
        )
    }

    fn commit_installer(&self, message: &str, bytes: &[u8]) -> Result<(), String> {
        self.write_installer(bytes)?;
        run_git(self.root(), &["add", INSTALLER_PATH])?;
        run_git(self.root(), &["commit", "-q", "-m", message])
    }
}

fn run_git(working_dir: &Path, args: &[&str]) -> Result<(), String> {
    let output = Command::new("git")
        .args(args)
        .current_dir(working_dir)
        .output()
        .map_err(|error| format!("failed to run git {args:?}: {error}"))?;
    if output.status.success() {
        Ok(())
    } else {
        Err(format!(
            "git {args:?} failed\nstdout:\n{}\nstderr:\n{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        ))
    }
}