Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

requirements.authoring.search_accounting.entry_tags

Requirements index · View definition

evidence Valid

Requirement

Each matches entry MUST have a short string tag, unique within its result, for selection by finish_search. Entries under not_listed MUST NOT receive selectable tags.

Rationale

Obligations

  1. Each matches entry has a short string tag.
  2. Tags are unique within a result.
  3. not_listed entries get no selectable tag.
  4. Tags can be used for selection by finish_search.

Coverage

  • Short string tag, unique within a result.
    • src/searches.rs#mod[tests]/fn[delivered_searches_including_empty_results_need_explicit_completion] collects each entry’s tag with as_str().unwrap(). That proves each tag is a string.
    • It asserts the tags equal ["1","2"]. That proves they are short and distinct for a multi-entry result.
    • It also asserts no entry carries a hash field.
    • Other tests in tools.rs assert exact entries with "tag":"1" and "tag":"2". I saw these only as search snippets and did not rely on them.
  • No tag on not_listed entries. src/authoring/tools.rs#mod[tests]/fn[listings_and_searches_name_untracked_files_without_their_contents] has a named helper. For every not_listed entry it asserts reason == "untracked" and entry.get("tag").is_none(). The test checks this for list_files, ripgrep and ast_grep. It runs with the root path, with src given in several path forms, and with a nonempty not_listed. It also checks that not_listed is absent when nothing untracked matches.
  • Selection by finish_search. src/authoring/pages.rs#mod[tests]/fn[search_pages_are_accounted_only_when_delivered_and_replay_stays_closed] finishes a search with used:[second["matches"][0]["tag"]] on both ripgrep and ast_grep. It checks that exactly one input is recorded and that its item equals the entry’s item. It also checks that a tag from another page’s result is rejected. That shows tags select the right entry and are scoped per result.

Residual concern The tests do not directly check uniqueness on a large multi-entry page. I looked at pages.rs#impl[ResultPages]/fn[deliver] to judge whether that matters. It assigns tags from an incrementing counter, so a larger page would not behave differently. This is not a gap.

All obligations have tests that assert their outcomes.

Inputs

Implementation

Input 5: outline src/authoring/pages.rs impl[ResultPages]/fn[deliver]
    /// Returns `listing` whole when its JSON is within [`PAGE_LIMIT`], and
    /// otherwise its first page, keeping the rest for `next_page`. Only the
    /// returned page's inputs are delivered.
    // {impl}`requirements.authoring.delivered_inputs`
    // {impl}`requirements.authoring.tool_descriptions.special_cases`
    // {impl}`requirements.authoring.not_listed`
    pub(crate) fn deliver(
        &mut self,
        sources: &AssessmentSources,
        mut listing: Listing,
    ) -> io::Result<ToolDelivery> {
        // Tags are attached before sizing, and never assigned to not_listed.
        // {impl}`requirements.authoring.search_accounting.entry_tags`
        let search = listing.arrays.iter().position(|key| *key == "matches");
        let instructions = search.is_some() && self.searches.needs_instructions();
        if let Some(search) = search {
            let mut tag = 0;
            for (array, entry) in &mut listing.entries {
                if *array == search {
                    tag += 1;
                    entry["tag"] = json!(tag.to_string());
                }
            }
        }
        let values: Vec<&Value> = listing.entries.iter().map(|(_, value)| value).collect();
        let indexes: Vec<usize> = listing.entries.iter().map(|(index, _)| *index).collect();
        let owned: Vec<Value> = values.iter().map(|value| (*value).clone()).collect();
        let definitions = if listing.evidence {
            sources.additional_definitions(&owned)?
        } else {
            Vec::new()
        };
        let mut whole = listing.render(&values, &indexes, &definitions, None, instructions);
        // Room for the redaction note only when it will be added.
        let reserve = if super::tools::needs_redaction_note(sources, &whole) {
            NOTE_RESERVE
        } else {
            0
        };
        if whole.to_string().len() + reserve <= PAGE_LIMIT {
            self.searches.prepare(sources, &mut whole)?;
            self.searches.delivered(&whole);
            return Ok(ToolDelivery {
                result: whole,
                inputs: delivered(&listing, owned, definitions),
            });
        }
        let accompanying = if listing.evidence {
            sources.definitions_each(&owned)?
        } else {
            vec![Vec::new(); owned.len()]
        };
        let total = values.len();
        let pages = paginate(&listing, &values, &accompanying, reserve, instructions);
        let tokens: Vec<String> = (1..pages.len()).map(|_| self.token()).collect();
        let mut rendered = Vec::new();
        for (number, range) in pages.iter().enumerate() {
            let (entries, page_indexes) = (&values[range.clone()], &indexes[range.clone()]);
            let definitions = page_definitions(entries, &accompanying[range.clone()]);
            let mut page = json!({
                "total_entries": total,
                "returned_entries": entries.len(),
                "next": tokens.get(number),
            });
            if tokens.get(number).is_some() {
                page["note"] = json!(PAGE_NOTE);
            }
            // {impl}`requirements.authoring.search_accounting.pagination`
            let mut result = listing.render(
                entries,
                page_indexes,
                &definitions,
                Some(page),
                instructions && number == 0,
            );
            self.searches.prepare(sources, &mut result)?;
            let inputs = delivered(
                &listing,
                entries.iter().map(|entry| (*entry).clone()).collect(),
                definitions,
            );
            rendered.push((result, inputs));
        }
        let mut rendered = rendered.into_iter();
        let (result, inputs) = rendered.next().expect("a paged result has a first page");
        self.searches.delivered(&result);
        for (token, page) in tokens.into_iter().zip(rendered) {
            self.pages.insert(token, page);
        }
        Ok(ToolDelivery { result, inputs })
    }

Tests

Input 2: outline src/authoring/pages.rs mod[tests]/fn[search_pages_are_accounted_only_when_delivered_and_replay_stays_closed]
  • File: src/authoring/pages.rs
  • Selector: mod[tests]/fn[search_pages_are_accounted_only_when_delivered_and_replay_stays_closed]
  • Kind: fn
  • src/authoring/pages.rs:662–738
    // {test}`requirements.authoring.search_accounting.pagination`
    // {test}`requirements.authoring.search_accounting.page_replay`
    // {test}`requirements.authoring.search_accounting.outstanding`
    // {test}`requirements.authoring.search_accounting.entry_tags`
    // {test}`requirements.authoring.search_accounting.result_ids`
    // {test}`requirements.authoring.search_accounting.instructions`
    // {test}`requirements.authoring.finish_search.completion`
    // {test}`requirements.authoring.finish_search.invalid`
    // {test}`requirements.authoring.result_pages`
    #[test]
    fn search_pages_are_accounted_only_when_delivered_and_replay_stays_closed() {
        let root = project();
        let source: String = (0..600)
            .map(|i| format!("fn needle_{i:04}() {{ let marker = 1; }}\n"))
            .collect();
        fs::write(root.path().join("src/lib.rs"), source).unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        for (tool, arguments) in [
            ("ripgrep", json!({"pattern":"marker","path":"src/lib.rs"})),
            (
                "ast_grep",
                json!({"language":"rust","rule":{"rule":{"pattern":"let marker = 1;"}}}),
            ),
        ] {
            let mut pages = ResultPages::default();
            let first = dispatch_paged(&sources, &mut pages, tool, &arguments)
                .unwrap()
                .result;
            let token = first["page"]["next"].as_str().unwrap().to_owned();
            assert_eq!(
                first["instructions"],
                super::super::approved_text("search_accounting.instructions", 0)
            );
            uuid::Uuid::parse_str(first["search_id"].as_str().unwrap()).unwrap();
            assert_eq!(
                pages.outstanding_searches(),
                [first["search_id"].as_str().unwrap()]
            );
            let undelivered = pages.pages[&token].0.clone();
            assert!(
                pages
                    .finish_search(&json!({"search_id":undelivered["search_id"],"used":[]}))
                    .is_err()
            );
            assert!(
                pages
                    .finish_search(&json!({"search_id":first["search_id"],
                "used":[undelivered["matches"][0]["tag"]]}))
                    .is_err()
            );
            let second = pages.next_page(&token).unwrap().result;
            uuid::Uuid::parse_str(second["search_id"].as_str().unwrap()).unwrap();
            assert_eq!(second, undelivered);
            assert_ne!(first["search_id"], second["search_id"]);
            assert!(second.get("instructions").is_none());
            assert_eq!(pages.outstanding_searches().len(), 2);
            let finished = pages
                .finish_search(&json!({"search_id":second["search_id"],
                "used":[second["matches"][0]["tag"]]}))
                .unwrap();
            assert_eq!(finished.inputs.len(), 1);
            assert_eq!(finished.inputs[0]["item"], second["matches"][0]["item"]);
            let replay = pages.next_page(&token).unwrap().result;
            assert_eq!(replay, second);
            assert_eq!(
                pages.outstanding_searches(),
                [first["search_id"].as_str().unwrap()]
            );
            pages
                .finish_search(&json!({"search_id":first["search_id"],"used":[]}))
                .unwrap();
            assert!(pages.outstanding_searches().is_empty());
            assert!(sources.recorded_inputs().is_empty());
            assert!(first.to_string().len() <= PAGE_LIMIT);
            assert!(second.to_string().len() <= PAGE_LIMIT);
        }
    }
Input 3: outline src/authoring/searches.rs mod[tests]/fn[delivered_searches_including_empty_results_need_explicit_completion]
    // {test}`requirements.authoring.search_accounting.result_ids`
    // {test}`requirements.authoring.search_accounting.entry_tags`
    // {test}`requirements.authoring.search_accounting.outstanding`
    // {test}`requirements.authoring.search_accounting.instructions`
    // {test}`requirements.authoring.finish_search.empty`
    // {test}`requirements.authoring.finish_search.invalid`
    // {test}`requirements.authoring.finish_search`
    #[test]
    fn delivered_searches_including_empty_results_need_explicit_completion() {
        let root = project();
        fs::write(
            root.path().join("src/lib.rs"),
            "fn first() {}\nfn second() {}\n",
        )
        .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let mut pages = ResultPages::default();
        assert!(dispatch_paged(&sources, &mut pages, "ripgrep", &json!({"pattern":"("})).is_err());
        assert!(pages.outstanding_searches().is_empty());
        let first = search(&sources, &mut pages, "fn");
        assert_eq!(
            first["instructions"],
            super::super::approved_text("search_accounting.instructions", 0)
        );
        let tags: Vec<_> = first["matches"]
            .as_array()
            .unwrap()
            .iter()
            .map(|entry| entry["tag"].as_str().unwrap())
            .collect();
        assert_eq!(tags, ["1", "2"]);
        for entry in first["matches"].as_array().unwrap() {
            assert!(entry.get("hash").is_none());
        }
        let empty = search(&sources, &mut pages, "absent");
        assert_eq!(empty["matches"], json!([]));
        assert!(empty.get("instructions").is_none());
        let repeated = search(&sources, &mut pages, "fn");
        assert!(repeated.get("instructions").is_none());
        let ids = [&first, &empty, &repeated]
            .map(|result| Uuid::parse_str(result["search_id"].as_str().unwrap()).unwrap());
        assert_eq!(
            ids.into_iter()
                .collect::<std::collections::BTreeSet<_>>()
                .len(),
            3
        );
        assert_eq!(pages.outstanding_searches().len(), 3);
        let mut other = ResultPages::default();
        let error = other
            .finish_search(&json!({"search_id":first["search_id"],"used":[]}))
            .err()
            .unwrap()
            .to_string();
        assert!(error.contains("delivered in this assessment"), "{error}");
        for result in [&first, &empty, &repeated] {
            let finished = pages
                .finish_search(&json!({"search_id":result["search_id"],"used":[]}))
                .unwrap();
            assert!(finished.inputs.is_empty());
            assert_eq!(
                finished.result,
                json!({"search_id":result["search_id"],"finished":true})
            );
        }
        assert!(pages.outstanding_searches().is_empty());
        assert!(sources.recorded_inputs().is_empty());
        for (tool, args) in [
            ("ripgrep", json!({"pattern":"absent","path":"src/lib.rs"})),
            (
                "ast_grep",
                json!({"language":"rust","rule":{"rule":{"pattern":"absent()"}}}),
            ),
        ] {
            let mut fresh = ResultPages::default();
            let result = dispatch_paged(&sources, &mut fresh, tool, &args)
                .unwrap()
                .result;
            assert_eq!(result["matches"], json!([]));
            assert_eq!(
                result["instructions"],
                super::super::approved_text("search_accounting.instructions", 0)
            );
            Uuid::parse_str(result["search_id"].as_str().unwrap()).unwrap();
            let again = dispatch_paged(&sources, &mut fresh, tool, &args)
                .unwrap()
                .result;
            assert_ne!(result["search_id"], again["search_id"]);
        }
    }
Input 4: outline src/authoring/tools.rs mod[tests]/fn[listings_and_searches_name_untracked_files_without_their_contents]
    // {test}`requirements.authoring.not_listed`
    // {test}`requirements.authoring.search_accounting.entry_tags`
    #[test]
    // {test}`requirements.authoring.read_denial`
    fn listings_and_searches_name_untracked_files_without_their_contents() {
        let root = project();
        fs::write(root.path().join("src/lib.rs"), "fn tracked() {}\n").unwrap();
        fs::write(
            root.path().join("habeas.toml"),
            "version = 1\n[evidence]\ndisallow = ['secret.rs']\n",
        )
        .unwrap();
        git(root.path(), &["init", "--quiet"]);
        git(root.path(), &["add", "."]);
        fs::write(root.path().join("untracked.rs"), "fn needle() {}\n").unwrap();
        fs::create_dir(root.path().join("drafts")).unwrap();
        fs::write(root.path().join("drafts/plan.txt"), "a needle here\n").unwrap();
        fs::write(root.path().join("secret.rs"), "fn needle() {}\n").unwrap();
        fs::create_dir_all(root.path().join("evidence")).unwrap();
        fs::write(root.path().join("evidence/note.txt"), "needle\n").unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let named = |result: &Value| {
            result["not_listed"]
                .as_array()
                .map(|entries| {
                    entries
                        .iter()
                        .map(|entry| {
                            assert_eq!(entry["reason"], "untracked");
                            assert!(entry.get("tag").is_none());
                            entry["path"].as_str().unwrap().to_owned()
                        })
                        .collect::<Vec<_>>()
                })
                .unwrap_or_default()
        };
        let listing = dispatch(&sources, "list_files", &json!({})).unwrap();
        assert_eq!(named(&listing.result), ["drafts", "untracked.rs"]);
        assert!(
            listing.result["entries"]
                .as_array()
                .unwrap()
                .iter()
                .any(|entry| entry["path"] == "src")
        );
        let search = dispatch(&sources, "ripgrep", &json!({"pattern": "needle"})).unwrap();
        assert_eq!(named(&search.result), ["drafts/plan.txt", "untracked.rs"]);
        let text = search.result.to_string();
        assert!(
            !text.contains("a needle here") && !text.contains("fn needle"),
            "{text}"
        );
        assert!(search.inputs.is_empty());
        let rust = dispatch(
            &sources,
            "ast_grep",
            &json!({"language": "rust", "rule": {"rule": {"pattern": "fn needle() {}"}}}),
        )
        .unwrap();
        assert_eq!(named(&rust.result), ["untracked.rs"]);
        for delivery in [&listing, &rust] {
            assert!(delivery.inputs.is_empty());
            let text = delivery.result.to_string();
            assert!(
                !text.contains("fn needle") && !text.contains("a needle here"),
                "{text}"
            );
        }

        // Nothing untracked matches: no not_listed.
        let none = dispatch(&sources, "ripgrep", &json!({"pattern": "tracked\\(\\)"})).unwrap();
        assert!(none.result.get("not_listed").is_none(), "{}", none.result);
        let inside = dispatch(&sources, "list_files", &json!({"path": "src"})).unwrap();
        assert!(
            inside.result.get("not_listed").is_none(),
            "{}",
            inside.result
        );
        fs::write(root.path().join("src/draft.rs"), "fn needle() {}\n").unwrap();
        for path in [
            "./src".to_owned(),
            "src/../src".to_owned(),
            root.path().join("src").to_string_lossy().into_owned(),
        ] {
            for (tool, arguments) in [
                ("list_files", json!({"path":path})),
                ("ripgrep", json!({"path":path,"pattern":"needle"})),
                (
                    "ast_grep",
                    json!({"path":path,"language":"rust","rule":{"rule":{"pattern":"fn needle() {}"}}}),
                ),
            ] {
                let delivery = dispatch(&sources, tool, &arguments).unwrap();
                assert_eq!(named(&delivery.result), ["src/draft.rs"], "{tool}: {path}");
                assert!(delivery.inputs.is_empty());
            }
        }
    }

Other sources

Input 1: requirements selection requirements.authoring.search_accounting.entry_tags
:::{req} search_accounting.entry_tags
Each `matches` entry MUST have a short string `tag`, unique within its result,
for selection by `finish_search`. Entries under `not_listed` MUST NOT receive
selectable tags.
:::