Skip to main content

vissue_core/
agent.rs

1//! Verbs shaped for a program rather than a person: structured rows, claiming,
2//! a body excerpt, and a hygiene checklist.
3
4use crate::error::Result;
5use serde_json::Value;
6use std::fmt::Write as _;
7
8use crate::catalog::{CatalogService, excerpt_from, format_body_excerpt, load_recs};
9use crate::config::Layout;
10use crate::error::Error;
11use crate::ops;
12use crate::report;
13use crate::store::{list_projects, load_all};
14use crate::views::ListQuery;
15
16/// Issue rows as JSON, filtered the same way [`report::list`] filters them.
17///
18/// # Errors
19///
20/// Returns an error if the corpus cannot be read, or the rows cannot be
21/// serialized.
22pub fn issues_json(
23    layout: &Layout,
24    project_filter: Option<&str>,
25    state_filter: Option<&str>,
26    ready_only: bool,
27) -> Result<Value> {
28    let recs = load_recs(layout)?;
29    let rows = CatalogService::from_recs(&recs).issues_rows(ListQuery {
30        project: project_filter.map(str::to_string),
31        state: state_filter.map(str::to_string),
32        ready: ready_only,
33        ..ListQuery::default()
34    })?;
35    Ok(serde_json::to_value(rows)?)
36}
37
38/// One issue as JSON, including its file and line range.
39///
40/// # Errors
41///
42/// Returns an error if the corpus cannot be read, `id` is not in it, or the
43/// detail cannot be serialized.
44pub fn show_json(layout: &Layout, id: &str) -> Result<Value> {
45    let recs = load_recs(layout)?;
46    let detail = CatalogService::from_recs(&recs).detail(id)?;
47    Ok(serde_json::to_value(detail)?)
48}
49
50/// Take an issue: move it to STARTED and stamp the claim.
51///
52/// # Errors
53///
54/// Returns an error if `id` is not in the corpus, the issue is DONE or
55/// CANCELLED, another identity holds it and `force` is false, or the file
56/// cannot be rewritten.
57pub fn claim(layout: &Layout, id: &str, force: bool) -> Result<String> {
58    let report = ops::claim(layout, id, force)?;
59    let detail = report::show(layout, id)?;
60    Ok(format!("{report}{detail}"))
61}
62
63/// The first lines of an issue's file range, capped and screened for secrets.
64///
65/// # Errors
66///
67/// Returns an error if `id` is not in the corpus, or the heading's file
68/// cannot be read.
69pub fn body_excerpt(layout: &Layout, id: &str) -> Result<String> {
70    let recs = load_recs(layout)?;
71    let rec = recs
72        .iter()
73        .find(|r| r.heading.id == id)
74        .ok_or_else(|| Error::IssueNotFound { id: id.to_string() })?;
75    Ok(format_body_excerpt(&excerpt_from(rec)?))
76}
77
78/// One issue's org text, in full, ready to write to a file.
79///
80/// [`body_excerpt`] is a preview and truncates; this does not. It is what a
81/// caller wants when the issue is being handed to someone as the thing to
82/// work from, rather than glanced at.
83///
84/// # Errors
85///
86/// Returns an error if `id` is not in the corpus, the heading's file cannot
87/// be read, or the heading looks like secret material.
88pub fn org_text(layout: &Layout, id: &str) -> Result<String> {
89    let recs = load_recs(layout)?;
90    let rec = recs
91        .iter()
92        .find(|r| r.heading.id == id)
93        .ok_or_else(|| Error::IssueNotFound { id: id.to_string() })?;
94    let mut text = crate::catalog::org_text_from(rec)?;
95    if !text.ends_with('\n') {
96        text.push('\n');
97    }
98    Ok(text)
99}
100
101/// Issues waiting on this one.
102///
103/// # Errors
104///
105/// Returns an error if the corpus cannot be read.
106pub fn waiting_on(layout: &Layout, id: &str) -> Result<String> {
107    report::backlinks(layout, id)
108}
109
110/// The agent and CI checklist: issues claimed but not actionable, claims that
111/// have gone stale, plus the corpus validation summary.
112///
113/// `stale_days` overrides the configured threshold when given.
114///
115/// # Errors
116///
117/// Returns an error if the corpus or configuration cannot be read.
118pub fn hygiene(layout: &Layout, stale_days: Option<i64>) -> Result<String> {
119    let mut out = String::new();
120    writeln!(out, "=== vissue hygiene ===")?;
121
122    // Compare ids, not rendered rows: `id_length` is configurable, so one id
123    // can be a prefix of another and a row match would pair the wrong issues.
124    let ready_ids: std::collections::HashSet<String> = issues_json(layout, None, None, true)?
125        .as_array()
126        .map(|rows| {
127            rows.iter()
128                .filter_map(|row| row["id"].as_str().map(str::to_string))
129                .collect()
130        })
131        .unwrap_or_default();
132    let mut started_not_ready = 0usize;
133    for (project, h) in load_all(layout)? {
134        if h.state != "STARTED" || ready_ids.contains(&h.id) {
135            continue;
136        }
137        started_not_ready += 1;
138        writeln!(
139            out,
140            "[warn] STARTED but not ready (blockers?): {} ({project})  {}",
141            h.id, h.title
142        )?;
143    }
144
145    let threshold = match stale_days {
146        Some(d) => d,
147        None => {
148            crate::config::VissueConfig::load(layout)?
149                .issues
150                .stale_claim_days
151        }
152    };
153    let today = chrono::Local::now().date_naive();
154    let mut stale_claims = 0usize;
155    let mut unclaimed_started = 0usize;
156    for (project, h) in load_all(layout)? {
157        if h.state != "STARTED" {
158            continue;
159        }
160        match h.claimed_by() {
161            None => {
162                unclaimed_started += 1;
163                writeln!(out, "[warn] STARTED with no claimant: {} ({project})", h.id)?;
164            }
165            Some(who) => {
166                if let Some(days) = h.claim_age_days(today)
167                    && days > threshold
168                {
169                    stale_claims += 1;
170                    writeln!(
171                        out,
172                        "[warn] claim held {days}d (over {threshold}d): {} by {who} ({project})",
173                        h.id
174                    )?;
175                }
176            }
177        }
178    }
179
180    let check = report::check(layout)?;
181    if check.errors == 0 {
182        writeln!(out, "[ok] check passed")?;
183    } else {
184        writeln!(out, "[fail] check found {} error(s)", check.errors)?;
185        for line in check.text.lines().filter(|l| l.starts_with("[err]")) {
186            writeln!(out, "{line}")?;
187        }
188    }
189    writeln!(
190        out,
191        "summary: started_not_ready={started_not_ready} stale_claims={stale_claims} unclaimed_started={unclaimed_started} projects={} errors={} warnings={}",
192        list_projects(layout)?.len(),
193        check.errors,
194        check.warnings
195    )?;
196    Ok(out)
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202    use crate::catalog::secret_marker;
203    use crate::config::DEFAULT_PREFIX;
204    use crate::ops::{CreateOpts, create, update};
205    use crate::store::IssueDoc;
206    use std::fs;
207
208    fn layout_with_two_issues() -> (tempfile::TempDir, Layout, String, String) {
209        let dir = tempfile::tempdir().unwrap();
210        let layout = Layout::new(dir.path(), DEFAULT_PREFIX);
211        fs::create_dir_all(layout.projects_dir()).unwrap();
212        create(&layout, "sample", "first", CreateOpts::default()).unwrap();
213        create(&layout, "sample", "blocker", CreateOpts::default()).unwrap();
214        let doc = IssueDoc::parse_file("sample", &layout.project_issues_path("sample")).unwrap();
215        let first = doc.headings[0].id.clone();
216        let blocker = doc.headings[1].id.clone();
217        (dir, layout, first, blocker)
218    }
219
220    #[test]
221    fn claim_moves_an_open_issue_to_started() {
222        let (_dir, layout, first, _blocker) = layout_with_two_issues();
223        let text = claim(&layout, &first, false).unwrap();
224        assert!(text.starts_with(&format!("claimed {first}")), "{text}");
225        assert!(text.contains("State:    STARTED"), "{text}");
226    }
227
228    #[test]
229    fn claim_refuses_a_closed_issue() {
230        let (_dir, layout, first, _blocker) = layout_with_two_issues();
231        update(&layout, &first, Some("DONE"), None, None, None).unwrap();
232        let err = claim(&layout, &first, false).unwrap_err();
233        assert!(err.to_string().contains("cannot claim"), "{err}");
234    }
235
236    #[test]
237    fn ready_json_drops_blocked_issues() {
238        let (_dir, layout, first, blocker) = layout_with_two_issues();
239        update(&layout, &first, None, None, Some(&blocker), None).unwrap();
240        let rows = issues_json(&layout, None, None, true).unwrap();
241        let ids: Vec<&str> = rows
242            .as_array()
243            .unwrap()
244            .iter()
245            .map(|r| r["id"].as_str().unwrap())
246            .collect();
247        assert_eq!(ids, vec![blocker.as_str()], "{rows}");
248    }
249
250    #[test]
251    fn show_json_carries_the_file_range() {
252        let (_dir, layout, first, _blocker) = layout_with_two_issues();
253        let row = show_json(&layout, &first).unwrap();
254        assert_eq!(row["id"].as_str(), Some(first.as_str()));
255        assert_eq!(row["project"].as_str(), Some("sample"));
256        assert!(
257            row["file"].as_str().unwrap().contains("issues.org:"),
258            "{row}"
259        );
260    }
261
262    #[test]
263    fn hygiene_flags_a_started_issue_that_is_blocked() {
264        let (_dir, layout, first, blocker) = layout_with_two_issues();
265        update(&layout, &first, Some("STARTED"), None, None, None).unwrap();
266        // Blocking would flip the state, so write the edge without the state move.
267        let path = layout.project_issues_path("sample");
268        let mut doc = IssueDoc::parse_file("sample", &path).unwrap();
269        doc.headings
270            .iter_mut()
271            .find(|h| h.id == first)
272            .unwrap()
273            .properties
274            .insert("BLOCKED_BY".into(), blocker.clone());
275        doc.write().unwrap();
276
277        let text = hygiene(&layout, None).unwrap();
278        assert!(text.contains("STARTED but not ready"), "{text}");
279        assert!(text.contains("started_not_ready=1"), "{text}");
280        assert!(text.contains("[ok] check passed"), "{text}");
281    }
282
283    #[test]
284    fn body_excerpt_returns_the_heading_range() {
285        let dir = tempfile::tempdir().unwrap();
286        let layout = Layout::new(dir.path(), DEFAULT_PREFIX);
287        fs::create_dir_all(layout.projects_dir()).unwrap();
288        create(
289            &layout,
290            "sample",
291            "documented",
292            CreateOpts {
293                body: Some("Scope: the excerpt path.\nDone-when: it reads back."),
294                ..Default::default()
295            },
296        )
297        .unwrap();
298        let doc = IssueDoc::parse_file("sample", &layout.project_issues_path("sample")).unwrap();
299        let text = body_excerpt(&layout, &doc.headings[0].id).unwrap();
300        assert!(text.contains("Scope: the excerpt path."), "{text}");
301        assert!(text.contains("Done-when: it reads back."), "{text}");
302    }
303
304    #[test]
305    fn the_secret_screen_reads_shapes_not_substrings() {
306        // Suppressed: the shapes a credential is actually written in.
307        for carrier in [
308            // Assembled rather than written out: a literal PEM header in a
309            // source file is exactly what the private-key hook looks for.
310            concat!("-----BEGIN OPENSSH ", "PRIVATE KEY-----"),
311            "aws_secret_access_key = wJalrXUtnFEMI",
312            "Authorization: Bearer abcdefghijklmno",
313            "api_key = 9f8e7d6c5b4a3210ff",
314            "token: ghp_0123456789abcdefghij",
315            "AKIAIOSFODNN7EXAMPLE is the key",
316        ] {
317            assert!(
318                secret_marker(carrier).is_some(),
319                "missed a credential: {carrier:?}"
320            );
321        }
322        // Not suppressed: ordinary prose. A substring screen flags every one
323        // of these -- "making" holds "aki", "task-force" holds "sk-".
324        for prose in [
325            "Scope: read the header block before the first record.",
326            "making the parser reject a bad manifest",
327            "the task-force agreed on the schema",
328            "deployments in Asia are slower",
329            "next-token: reviewed by the release owner",
330            "Deadline: the parser lands before the notes.",
331            "See the design note for the token grammar.",
332        ] {
333            assert_eq!(secret_marker(prose), None, "false positive: {prose:?}");
334        }
335    }
336
337    #[test]
338    fn body_excerpt_suppresses_apparent_secrets() {
339        let dir = tempfile::tempdir().unwrap();
340        let layout = Layout::new(dir.path(), DEFAULT_PREFIX);
341        fs::create_dir_all(layout.projects_dir()).unwrap();
342        create(
343            &layout,
344            "sample",
345            "leaky",
346            CreateOpts {
347                body: Some("token: api_key=whatever-it-was"),
348                ..Default::default()
349            },
350        )
351        .unwrap();
352        let doc = IssueDoc::parse_file("sample", &layout.project_issues_path("sample")).unwrap();
353        let text = body_excerpt(&layout, &doc.headings[0].id).unwrap();
354        assert!(text.contains("excerpt suppressed"), "{text}");
355        assert!(!text.contains("whatever-it-was"), "{text}");
356    }
357}