requirements.authoring.read_denial
Requirements index · View definition
Requirement
When source-access policy denies a path that a model tool call names explicitly, the harness MUST return a tool error naming the path and the reason it cannot be read, add no evidence input, and continue the assessment. Discovery and search MUST leave denied candidates out of their entries, reporting untracked ones under
. Malformed tool arguments and ordinary read failures MUST also return explanatory tool errors.
Rationale
The reviewed tests adequately check requirements.authoring.read_denial; I found no gaps. I worked from the supplied test text and requested no implementation source. The refinements read_denial.untracked, read_denial.build_output and read_denial.mandatory and the cited not_listed requirement are not reassessed here.
1. A denied explicit path returns a tool error naming the path and reason, adds no evidence input, and the assessment continues.
- Reasons covered:
- Generated evidence:
generated_evidence_is_excluded_from_reads_search_and_discoveryassertsPermissionDenied, that the message contains the path and “generated evidence”, and thatrecorded_inputs()is empty. It does this forhabeas,list_files,ripgrepandast_grep, including symlink aliases. - Disallow rule:
allowed_ignored_and_external_sources_are_discoverable_but_disallowed_descendants_are_not, the denied half ofcargo_output_is_discovered_and_read_without_building_or_allowing_other_target_files, andoutline_lists_nested_nodes_without_text_or_inputseach assertPermissionDenied. The cargo and outline tests also assert “disallowed” and the path. - Untracked:
untracked_diagnostics_name_git_add_and_an_allow_ruleasserts the message names the path,git addand an allow rule. It also checks that the harness stages and permits nothing itself. - Outside the project:
requests_through_symlinks_leaving_the_project_are_denialsandunpermitted_requests_outside_the_project_are_recoverable_tool_errorsassert “outside the project” across all tools.
- Generated evidence:
- Policy resolution: the
access.rstests exercise denial through symlink aliases,..components and disallowed ancestors. They assertPermissionDeniedand that the message contains the path. - Assessment continues:
a_read_through_a_symlink_leaving_the_project_returns_an_error_to_the_modelinmod.rsruns the realassessloop. It checks that the second request carries the path and reason, leaks no file content, and that the evidence omits the file.a_denied_read_returns_an_error_and_its_assessment_continuesintests/authoring_batch.rschecks a second request, a completed outcome,tool_failuresof 1, and no recorded input.explicit_untracked_reads_return_an_untracked_error_and_the_assessment_continuesintests/authoring_cli.rscovers thehabeas,ripgrep,ast_grepandlist_filestools.
2. Discovery and search leave denied candidates out of their entries and report untracked ones under not_listed.
- Evidence output, a disallowed subtree and untracked files are all kept out of entries. The tests that show this are
generated_evidence_is_excluded_from_reads_search_and_discovery,allowed_ignored_and_external_sources_are_discoverable_but_disallowed_descendants_are_not, the denied half ofcargo_output_is_discovered_and_read_without_building_or_allowing_other_target_files, andgit_tools_allow_staged_and_dirty_sources_but_hide_untracked_files. They coverlist_files,ripgrepandast_grep. listings_and_searches_name_untracked_files_without_their_contentschecksnot_listed. Each entry has reasonuntrackedand the path, and no contents appear. The array is omitted when nothing is untracked. The disallowed andevidence/files are not listed. Path variants for the three tools are covered.
3. Malformed arguments and ordinary read failures return explanatory tool errors.
- Malformed arguments, by tool:
ripgrep:search_records_nothing_clamps_at_eof_and_reports_failures.ast_grep:ast_grep_returns_innermost_nodes_of_the_language_and_reports_failures.list_files:failed_listings_return_explanatory_tool_errors.outline:outline_lists_nested_nodes_without_text_or_inputs.habeas:malformed_and_failed_reads_return_to_the_model_and_the_assessment_continues.github:additional_read_flow_searches_outlines_and_reads_a_rust_file.references:references_list_names_and_flattened_sites_without_recording_inputs.next_page:paged_inputs_carry_their_definitions_and_deliver_only_their_own_inputs.
- Ordinary read failures:
malformed_and_failed_reads_return_to_the_model_and_the_assessment_continuescovers a missing file, an absent item and a line past EOF. It asserts the kind is notPermissionDenied, that the message reaches the model in the second request, and that nothing is recorded.operating_system_permission_failures_are_ordinary_read_failuresandrequests_for_book_or_target_output_are_ordinary_read_failurescover OS permission failures and book or target output.
I found no plausible requirement-violating behavior that these tests would accept.
Inputs
Tests
Input 3: outline src/authoring/access.rs mod[tests]/fn[explicit_allow_overrides_defaults_but_disallow_wins_for_alias_targets]
- File:
src/authoring/access.rs - Selector:
mod[tests]/fn[explicit_allow_overrides_defaults_but_disallow_wins_for_alias_targets] - Kind:
fn src/authoring/access.rs:860–906
// {test}`requirements.configuration.evidence_paths`
// {test}`requirements.authoring.source_tools`
// {test}`requirements.authoring.read_denial`
// {test}`requirements.ci.input_containment`
#[test]
fn explicit_allow_overrides_defaults_but_disallow_wins_for_alias_targets() {
let root = tempfile::tempdir().unwrap();
let external = tempfile::tempdir().unwrap();
fs::create_dir_all(root.path().join("generated/private")).unwrap();
fs::create_dir(root.path().join("evidence")).unwrap();
fs::write(root.path().join("generated/ok.txt"), "generated\n").unwrap();
fs::write(root.path().join("generated/private/secret.txt"), "secret\n").unwrap();
fs::write(root.path().join("evidence/old.txt"), "old judgment\n").unwrap();
fs::write(external.path().join("outside.txt"), "outside\n").unwrap();
git(root.path(), &["init", "--quiet"]);
let external_toml = toml::Value::String(external.path().display().to_string());
fs::write(root.path().join("habeas.toml"), format!(
"version = 1\n[evidence]\nallow = ['generated', 'evidence', {external_toml}]\ndisallow = ['generated/private']\n"
)).unwrap();
let root = fs::canonicalize(root.path()).unwrap();
let access = SourceAccess::load(&root).unwrap();
for path in [
root.join("generated/ok.txt"),
root.join("evidence/old.txt"),
external.path().join("outside.txt"),
] {
assert!(access.file(&root, &path).is_ok(), "{}", path.display());
assert!(resolve_evidence_file(&root, path.to_str().unwrap()).is_ok());
}
let error = access
.file(&root, Path::new("generated/private/secret.txt"))
.unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
assert!(resolve_evidence_file(&root, "generated/private/secret.txt").is_err());
#[cfg(unix)]
{
std::os::unix::fs::symlink(
root.join("generated/private/secret.txt"),
root.join("generated/alias.txt"),
)
.unwrap();
let error = access
.file(&root, Path::new("generated/alias.txt"))
.unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
}
}
Input 4: outline src/authoring/access.rs mod[tests]/fn[workspace_configuration_with_credentials_is_readable_unless_disallowed]
- File:
src/authoring/access.rs - Selector:
mod[tests]/fn[workspace_configuration_with_credentials_is_readable_unless_disallowed] - Kind:
fn src/authoring/access.rs:974–996
// {test}`requirements.authoring.credentials`
// {test}`requirements.configuration.evidence_paths`
// {test}`requirements.authoring.read_denial`
// {test}`requirements.authoring.source_tools`
#[test]
fn workspace_configuration_with_credentials_is_readable_unless_disallowed() {
let root = tempfile::tempdir().unwrap();
let config = "version = 1\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'fixture'\napi_key = 'TEST_KEY'\n";
fs::write(root.path().join("habeas.toml"), config).unwrap();
let access = SourceAccess::load(root.path()).unwrap();
assert!(access.file(root.path(), Path::new("habeas.toml")).is_ok());
fs::write(
root.path().join("habeas.toml"),
format!("{config}\n[evidence]\ndisallow = ['habeas.toml']\n"),
)
.unwrap();
let error = SourceAccess::load(root.path())
.unwrap()
.file(root.path(), Path::new("habeas.toml"))
.unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
assert!(!error.to_string().contains("TEST_KEY"));
}
Input 5: outline src/authoring/access.rs mod[tests]/fn[disallowed_ancestors_cannot_redirect_reads_into_allowed_targets]
- File:
src/authoring/access.rs - Selector:
mod[tests]/fn[disallowed_ancestors_cannot_redirect_reads_into_allowed_targets] - Kind:
fn src/authoring/access.rs:998–1035
// {test}`requirements.configuration.evidence_paths`
// {test}`requirements.authoring.source_tools`
// {test}`requirements.authoring.read_denial`
// {test}`requirements.ci.input_containment`
#[cfg(unix)]
#[test]
fn disallowed_ancestors_cannot_redirect_reads_into_allowed_targets() {
let root = tempfile::tempdir().unwrap();
for directory in ["private", "public", "sub"] {
fs::create_dir(root.path().join(directory)).unwrap();
}
fs::write(root.path().join("public/file.txt"), "public source\n").unwrap();
std::os::unix::fs::symlink("../public", root.path().join("private/link")).unwrap();
fs::write(
root.path().join("habeas.toml"),
"version = 1\n[evidence]\nallow = ['public']\ndisallow = ['private']\n",
)
.unwrap();
let access = SourceAccess::load(root.path()).unwrap();
assert!(
access
.file(root.path(), Path::new("public/file.txt"))
.is_ok()
);
for path in [
"private/link/file.txt",
"sub/../private/link/file.txt",
"private/link",
] {
let error = access.path(root.path(), Path::new(path)).unwrap_err();
assert_eq!(
error.kind(),
io::ErrorKind::PermissionDenied,
"{path}: {error}"
);
assert!(error.to_string().contains(path), "{error}");
}
}
Input 6: outline src/authoring/access.rs mod[tests]/fn[policy_resolves_symlinks_before_parent_components_without_allowing_wrong_subtrees]
- File:
src/authoring/access.rs - Selector:
mod[tests]/fn[policy_resolves_symlinks_before_parent_components_without_allowing_wrong_subtrees] - Kind:
fn src/authoring/access.rs:1064–1140
// {test}`requirements.configuration.evidence_paths`
// {test}`requirements.authoring.source_tools`
// {test}`requirements.authoring.read_denial`
// {test}`requirements.ci.input_containment`
#[cfg(unix)]
#[test]
fn policy_resolves_symlinks_before_parent_components_without_allowing_wrong_subtrees() {
let root = tempfile::tempdir().unwrap();
for directory in ["actual/nested", "actual/private", "private"] {
fs::create_dir_all(root.path().join(directory)).unwrap();
}
fs::write(root.path().join("actual/private/file.txt"), "actual\n").unwrap();
fs::write(root.path().join("private/file.txt"), "wrong subtree\n").unwrap();
std::os::unix::fs::symlink(root.path().join("actual/nested"), root.path().join("alias"))
.unwrap();
git(root.path(), &["init", "--quiet"]);
fs::write(
root.path().join("habeas.toml"),
"version = 1\n[evidence]\nallow = ['alias/../private']\n",
)
.unwrap();
let access = SourceAccess::load(root.path()).unwrap();
assert!(
access
.file(root.path(), Path::new("actual/private/file.txt"))
.is_ok()
);
assert!(
access
.file(root.path(), Path::new("alias/../private/file.txt"))
.is_ok()
);
assert_eq!(
access
.file(root.path(), Path::new("private/file.txt"))
.unwrap_err()
.kind(),
io::ErrorKind::PermissionDenied
);
fs::write(
root.path().join("habeas.toml"),
"version = 1\n[evidence]\nallow = ['.']\ndisallow = ['alias/../private']\n",
)
.unwrap();
let access = SourceAccess::load(root.path()).unwrap();
for denied in ["actual/private/file.txt", "alias/../private/file.txt"] {
assert_eq!(
access
.file(root.path(), Path::new(denied))
.unwrap_err()
.kind(),
io::ErrorKind::PermissionDenied
);
assert!(resolve_evidence_file(root.path(), denied).is_err());
}
assert!(
access
.file(root.path(), Path::new("private/file.txt"))
.is_ok()
);
fs::write(
root.path().join("habeas.toml"),
"version = 1\n[evidence]\nallow = ['actual/private']\n",
)
.unwrap();
let access = SourceAccess::load(root.path()).unwrap();
assert_eq!(
access
.file(
root.path(),
Path::new("actual/private/../../private/file.txt")
)
.unwrap_err()
.kind(),
io::ErrorKind::PermissionDenied
);
}
Input 7: outline src/authoring/access.rs mod[tests]/fn[inherited_out_dir_is_ignored_and_metadata_failure_preserves_ordinary_reads]
- File:
src/authoring/access.rs - Selector:
mod[tests]/fn[inherited_out_dir_is_ignored_and_metadata_failure_preserves_ordinary_reads] - Kind:
fn src/authoring/access.rs:1142–1185
// {test}`requirements.authoring.generated_inputs`
// {test}`requirements.authoring.source_tools`
// {test}`requirements.authoring.read_denial`
#[test]
fn inherited_out_dir_is_ignored_and_metadata_failure_preserves_ordinary_reads() {
if let Some(root) = std::env::var_os("HABEAS_TEST_OUT_DIR_PROBE_ROOT") {
let root = PathBuf::from(root);
let access = SourceAccess::load(&root).unwrap();
assert!(access.generated.is_empty());
assert!(access.file(&root, Path::new("tracked.txt")).is_ok());
let inherited = PathBuf::from(std::env::var_os("OUT_DIR").unwrap());
let error = access
.file(&root, &inherited.join("unrelated.txt"))
.unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
return;
}
let root = tempfile::tempdir().unwrap();
let unrelated = tempfile::tempdir().unwrap();
fs::write(root.path().join("tracked.txt"), "ordinary source\n").unwrap();
fs::write(
root.path().join("Cargo.toml"),
"deliberately invalid TOML [\n",
)
.unwrap();
fs::write(
unrelated.path().join("unrelated.txt"),
"unrelated generated data\n",
)
.unwrap();
git(root.path(), &["init", "--quiet"]);
git(root.path(), &["add", "."]);
let output = Command::new(std::env::current_exe().unwrap())
.args(["--exact", "authoring::access::tests::inherited_out_dir_is_ignored_and_metadata_failure_preserves_ordinary_reads", "--nocapture"])
.env("HABEAS_TEST_OUT_DIR_PROBE_ROOT", root.path())
.env("OUT_DIR", unrelated.path())
.output().unwrap();
assert!(
output.status.success(),
"{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}
Input 8: outline src/authoring/inputs.rs mod[tests]/fn[mandatory_git_inputs_require_staging_declarations_sources_and_terms]
- File:
src/authoring/inputs.rs - Selector:
mod[tests]/fn[mandatory_git_inputs_require_staging_declarations_sources_and_terms] - Kind:
fn src/authoring/inputs.rs:1120–1187
// {test}`requirements.authoring.source_tools`
// {test}`requirements.authoring.mandatory_inputs`
// {test}`requirements.definitions.authoring_inputs`
// {test}`requirements.authoring_input`
// {test}`requirements.references.authoring_inputs`
// {test}`requirements.authoring.read_denial`
// {test}`requirements.references.discovery`
#[test]
fn mandatory_git_inputs_require_staging_declarations_sources_and_terms() {
let root = project();
git(root.path(), &["init", "--quiet"]);
git(root.path(), &["add", "Cargo.toml", "book.toml"]);
let error = AssessmentSources::prepare(root.path(), "requirements.ready")
.err()
.unwrap();
assert!(
error.to_string().contains("md/requirements.md")
&& error.to_string().contains("git add"),
"{error}"
);
git(root.path(), &["add", "md"]);
fs::write(
root.path().join("src/lib.rs"),
format!(
"// {}\nfn ready() {{}}\n",
role("test", "requirements.ready")
),
)
.unwrap();
// Discovery does not consider an untracked source, so its reference is
// not yet an input; staging it makes the source mandatory.
let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
let supplied = serde_json::to_string(sources.mandatory_inputs()).unwrap();
assert!(!supplied.contains("src/lib.rs"), "{supplied}");
git(root.path(), &["add", "src"]);
let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
let supplied = serde_json::to_string(sources.mandatory_inputs()).unwrap();
assert!(supplied.contains("src/lib.rs"), "{supplied}");
fs::write(
root.path().join("md/terms.md"),
":::{definition} ready\n:phrase: ready\nReady to proceed.\n:::\n",
)
.unwrap();
fs::write(
root.path().join("src/lib.rs"),
format!(
"// {} {}\nfn ready() {{}}\n",
role("test", "requirements.ready"),
role("term", "terms.ready")
),
)
.unwrap();
let error = AssessmentSources::prepare(root.path(), "requirements.ready")
.err()
.unwrap();
assert!(
error.to_string().contains("md/terms.md") && error.to_string().contains("git add"),
"{error}"
);
git(root.path(), &["add", "md/terms.md"]);
let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
assert!(
sources
.mandatory_inputs()
.iter()
.any(|input| input["definition"] == "terms.ready")
);
}
Input 9: outline src/authoring/inputs.rs mod[tests]/fn[mandatory_inputs_through_symlinks_leaving_the_project_abort_preparation]
- File:
src/authoring/inputs.rs - Selector:
mod[tests]/fn[mandatory_inputs_through_symlinks_leaving_the_project_abort_preparation] - Kind:
fn src/authoring/inputs.rs:1189–1213
// {test}`requirements.authoring.read_denial`
#[cfg(unix)]
// {test}`requirements.references.anchors`
#[test]
fn mandatory_inputs_through_symlinks_leaving_the_project_abort_preparation() {
let root = project();
let outside = tempfile::tempdir().unwrap();
fs::write(outside.path().join("secret.rs"), "fn secret() {}\n").unwrap();
std::os::unix::fs::symlink(
outside.path().join("secret.rs"),
root.path().join("src/escape.rs"),
)
.unwrap();
fs::write(
root.path().join("md/requirements.md"),
":::{req} ready\n:impl: src/escape.rs\nThe project MUST be ready.\n:::\n",
)
.unwrap();
let error = AssessmentSources::prepare(root.path(), "requirements.ready")
.err()
.unwrap();
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
assert!(error.to_string().contains("src/escape.rs"), "{error}");
assert!(error.to_string().contains("outside the project"), "{error}");
}
Input 10: outline src/authoring/inputs.rs mod[tests]/fn[disallowed_mandatory_inputs_abort_preparation]
- File:
src/authoring/inputs.rs - Selector:
mod[tests]/fn[disallowed_mandatory_inputs_abort_preparation] - Kind:
fn src/authoring/inputs.rs:1215–1231
// {test}`requirements.configuration.evidence_paths`
// {test}`requirements.authoring.mandatory_inputs`
// {test}`requirements.authoring.read_denial`
#[test]
fn disallowed_mandatory_inputs_abort_preparation() {
let root = project();
fs::write(
root.path().join("habeas.toml"),
"version = 1\n[evidence]\ndisallow = ['md/requirements.md']\n",
)
.unwrap();
let error = AssessmentSources::prepare(root.path(), "requirements.ready")
.err()
.unwrap();
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
assert!(error.to_string().contains("md/requirements.md"), "{error}");
}
Input 11: outline src/authoring/inputs.rs mod[tests]/fn[unreadable_or_denied_anchors_fail_before_inference]
- File:
src/authoring/inputs.rs - Selector:
mod[tests]/fn[unreadable_or_denied_anchors_fail_before_inference] - Kind:
fn src/authoring/inputs.rs:1568–1624
// {test}`requirements.references.anchors`
// {test}`requirements.authoring.read_denial`
// {test}`requirements.authoring.read_denial.mandatory`
#[test]
// {test}`requirements.authoring.mandatory_inputs`
fn unreadable_or_denied_anchors_fail_before_inference() {
let root = project();
fs::write(
root.path().join("md/requirements.md"),
":::{req} ready\n:impl: skills/missing.md\nThe project MUST be ready.\n:::\n",
)
.unwrap();
let error = AssessmentSources::prepare(root.path(), "requirements.ready")
.err()
.unwrap();
assert!(
error
.to_string()
.contains("requirements.ready: cannot read :impl: anchor skills/missing.md"),
"{error}"
);
// An anchor naming a node its existing file lacks fails the same way.
fs::write(root.path().join("src/lib.rs"), "fn present() {}\n").unwrap();
fs::write(
root.path().join("md/requirements.md"),
":::{req} ready\n:impl: src/lib.rs#fn[missing]\nThe project MUST be ready.\n:::\n",
)
.unwrap();
let error = AssessmentSources::prepare(root.path(), "requirements.ready")
.err()
.unwrap();
assert!(
error
.to_string()
.contains("cannot read :impl: anchor src/lib.rs#fn[missing]"),
"{error}"
);
fs::create_dir_all(root.path().join("private")).unwrap();
fs::write(root.path().join("private/skill.md"), "secret\n").unwrap();
fs::write(
root.path().join("md/requirements.md"),
":::{req} ready\n:impl: private/skill.md\nThe project MUST be ready.\n:::\n",
)
.unwrap();
fs::write(
root.path().join("habeas.toml"),
"version = 1\n[evidence]\ndisallow = ['private']\n",
)
.unwrap();
let error = AssessmentSources::prepare(root.path(), "requirements.ready")
.err()
.unwrap();
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
assert!(error.to_string().contains("private/skill.md"), "{error}");
}
Input 12: outline src/authoring/inputs.rs mod[tests]/fn[generated_evidence_anchors_are_omitted_unless_allowed_and_abort_when_disallowed]
- File:
src/authoring/inputs.rs - Selector:
mod[tests]/fn[generated_evidence_anchors_are_omitted_unless_allowed_and_abort_when_disallowed] - Kind:
fn src/authoring/inputs.rs:1798–1869
// {test}`requirements.authoring.mandatory_inputs`
// {test}`requirements.authoring.read_denial`
#[test]
fn generated_evidence_anchors_are_omitted_unless_allowed_and_abort_when_disallowed() {
let root = project();
fs::create_dir_all(root.path().join("evidence")).unwrap();
fs::write(root.path().join("evidence/report.md"), "# Report\n").unwrap();
#[cfg(unix)]
std::os::unix::fs::symlink("evidence", root.path().join("alias")).unwrap();
let declaration = |anchor: &str| {
fs::write(
root.path().join("md/requirements.md"),
format!(":::{{req}} ready\n:test: {anchor}\nThe project MUST be ready.\n:::\n"),
)
.unwrap();
};
let has_file = |sources: &AssessmentSources, file: &str| {
sources
.mandatory_inputs()
.iter()
.any(|input| input["file"] == file)
};
// Default exclusion omits the anchor instead of aborting.
declaration("evidence/report.md");
let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
assert!(
!has_file(&sources, "evidence/report.md"),
"{:#?}",
sources.mandatory_inputs()
);
assert_eq!(sources.mandatory_inputs().len(), 1);
// A symlink alias into `evidence/` is omitted too.
#[cfg(unix)]
{
declaration("alias/report.md");
let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
assert!(
!has_file(&sources, "alias/report.md"),
"{:#?}",
sources.mandatory_inputs()
);
assert_eq!(sources.mandatory_inputs().len(), 1);
}
// An explicit allow permits the selection.
declaration("evidence/report.md");
fs::write(
root.path().join("habeas.toml"),
"version = 1\n[evidence]\nallow = ['evidence/report.md']\n",
)
.unwrap();
let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
assert!(
has_file(&sources, "evidence/report.md"),
"{:#?}",
sources.mandatory_inputs()
);
// An explicit disallow aborts before inference.
fs::write(
root.path().join("habeas.toml"),
"version = 1\n[evidence]\ndisallow = ['evidence']\n",
)
.unwrap();
let error = AssessmentSources::prepare(root.path(), "requirements.ready")
.err()
.unwrap();
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
assert!(error.to_string().contains("evidence/report.md"), "{error}");
}
Input 13: outline src/authoring/mod.rs mod[tests]/fn[malformed_and_failed_reads_return_to_the_model_and_the_assessment_continues]
- File:
src/authoring/mod.rs - Selector:
mod[tests]/fn[malformed_and_failed_reads_return_to_the_model_and_the_assessment_continues] - Kind:
fn src/authoring/mod.rs:2052–2103
// {test}`requirements.authoring.read_denial`
// {test}`requirements.authoring.tool_descriptions.special_cases`
#[tokio::test]
async fn malformed_and_failed_reads_return_to_the_model_and_the_assessment_continues() {
for read in [
json!({"file": "src/lib.rs", "line_start": "one"}),
json!({"file": "src/lib.rs"}),
json!({"file": "src/lib.rs", "item": "fn[work]", "requirements": "*"}),
json!({"file": "missing.rs", "line_start": 1}),
json!({"file": "src/lib.rs", "item": "fn[absent]"}),
json!({"file": "src/lib.rs", "line_start": 99}),
] {
let project = inputs::tests::project();
fs::write(project.path().join("src/lib.rs"), "fn work() {}\n").unwrap();
let mut sources =
AssessmentSources::prepare(project.path(), "requirements.ready").unwrap();
let state = tempfile::tempdir().unwrap();
let mut usage =
UsageLog::start(state.path(), project.path(), &sources.subject_name).unwrap();
let provider = ReadingProvider {
read: read.clone(),
requests: RefCell::default(),
};
let failure = tools::dispatch(&sources, "habeas", &read)
.err()
.unwrap_or_else(|| panic!("{read} fails"));
assert_ne!(failure.kind(), io::ErrorKind::PermissionDenied, "{read}");
let (_, evidence) = assess(&provider, &mut sources, &mut usage)
.await
.unwrap_or_else(|error| panic!("{read}: {error}"));
// The failure went back to the model as a tool error, and the model
// then submitted in a second request.
let requests = provider.requests.borrow();
assert_eq!(requests.len(), 2, "{read}");
let message =
serde_json::to_string(&line_numbers::without_source_lines(&failure.to_string()))
.unwrap();
let message = message.trim_matches('"');
assert!(!requests[0].to_string().contains(message), "{read}");
assert!(requests[1].to_string().contains(message), "{read}");
assert!(
evidence["inputs"]
.as_array()
.unwrap()
.iter()
.all(|input| input
.get("file")
.is_none_or(|file| file != "src/lib.rs" && file != "missing.rs")),
"{read}: {evidence}"
);
}
}
Input 14: outline src/authoring/mod.rs mod[tests]/fn[a_read_through_a_symlink_leaving_the_project_returns_an_error_to_the_model]
- File:
src/authoring/mod.rs - Selector:
mod[tests]/fn[a_read_through_a_symlink_leaving_the_project_returns_an_error_to_the_model] - Kind:
fn src/authoring/mod.rs:2105–2136
// {test}`requirements.authoring.read_denial`
#[cfg(unix)]
// {test}`requirements.authoring.tool_descriptions.special_cases`
#[tokio::test]
async fn a_read_through_a_symlink_leaving_the_project_returns_an_error_to_the_model() {
let project = inputs::tests::project();
let outside = tempfile::tempdir().unwrap();
fs::write(outside.path().join("secret.rs"), "fn secret() {}\n").unwrap();
std::os::unix::fs::symlink(
outside.path().join("secret.rs"),
project.path().join("src/escape.rs"),
)
.unwrap();
let mut sources = AssessmentSources::prepare(project.path(), "requirements.ready").unwrap();
let state = tempfile::tempdir().unwrap();
let mut usage =
UsageLog::start(state.path(), project.path(), &sources.subject_name).unwrap();
let provider = ReadingProvider {
read: json!({"file": "src/escape.rs", "line_start": 1}),
requests: RefCell::default(),
};
let (_, evidence) = assess(&provider, &mut sources, &mut usage).await.unwrap();
// The denial went back to the model, naming the path and the reason,
// and the assessment continued without recording the file.
let requests = provider.requests.borrow();
assert_eq!(requests.len(), 2);
let delivered = requests[1].to_string();
assert!(delivered.contains("src/escape.rs"), "{delivered}");
assert!(delivered.contains("outside the project"), "{delivered}");
assert!(!delivered.contains("fn secret"), "{delivered}");
assert!(!evidence.to_string().contains("escape.rs"), "{evidence}");
}
Input 15: outline src/authoring/pages.rs mod[tests]/fn[paged_inputs_carry_their_definitions_and_deliver_only_their_own_inputs]
- File:
src/authoring/pages.rs - Selector:
mod[tests]/fn[paged_inputs_carry_their_definitions_and_deliver_only_their_own_inputs] - Kind:
fn src/authoring/pages.rs:806–896
// {test}`requirements.authoring.result_pages`
// {test}`requirements.authoring.delivered_inputs`
// {test}`requirements.definitions.authoring_inputs`
// {test}`requirements.authoring.read_denial`
#[test]
// {test}`requirements.authoring.source_tools`
fn paged_inputs_carry_their_definitions_and_deliver_only_their_own_inputs() {
let root = project();
fs::write(
root.path().join("md/terms.md"),
":::{definition} value\n:phrase: value\nA useful value.\n:::\n",
)
.unwrap();
let term = role("term", "terms.value");
let mut source = String::new();
for index in 0..400 {
// Only the last function uses the term, so only its page needs it.
let comment = if index == 399 { term.as_str() } else { "plain" };
source.push_str(&format!(
"// {comment}\nfn needle_{index}() {{\n let text = \"padding padding padding\";\n}}\n\n"
));
}
fs::write(root.path().join("src/lib.rs"), source).unwrap();
let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
let mut pages = ResultPages::default();
let error = dispatch_paged(&sources, &mut pages, "next_page", &json!({}))
.err()
.unwrap();
assert!(
error.to_string().contains("token must be a string"),
"{error}"
);
let first = dispatch_paged(
&sources,
&mut pages,
"habeas",
&json!({"file":"src/lib.rs","line_start":1}),
)
.unwrap();
let delivered = all_pages(&mut pages, first);
let mut items = Vec::new();
for (number, page) in delivered.iter().enumerate() {
assert!(page.result.to_string().len() <= PAGE_LIMIT);
let inputs = page.result["inputs"].as_array().unwrap();
let definitions = page.result["definitions"].as_array().unwrap();
// A page's delivery is exactly its own inputs and definitions.
let mut expected = inputs.clone();
expected.extend(definitions.iter().cloned());
assert_eq!(page.inputs, expected);
let last = number == delivered.len() - 1;
assert_eq!(
definitions
.iter()
.any(|definition| definition["definition"] == "terms.value"),
last,
"page {number}: {definitions:?}"
);
items.extend(
inputs
.iter()
.map(|input| input["item"].as_str().unwrap().to_owned()),
);
}
let expected = (0..400)
.map(|index| format!("fn[needle_{index}]"))
.collect::<Vec<_>>();
assert_eq!(items, expected);
// A token is unknown to another assessment, and an unknown token is
// an explanatory tool error.
let token = delivered[0].result["page"]["next"].as_str().unwrap();
let mut other = ResultPages::default();
let error = other.next_page(token).err().unwrap();
assert!(error.to_string().contains("unknown page token"), "{error}");
let error = dispatch_paged(
&sources,
&mut pages,
"next_page",
&json!({"token":"not-a-token"}),
)
.err()
.unwrap();
assert!(
error.to_string().contains("valid only in the assessment"),
"{error}"
);
// A token's page comes back in the same shape when asked again.
let again =
dispatch_paged(&sources, &mut pages, "next_page", &json!({"token": token})).unwrap();
assert_eq!(again.result, delivered[1].result);
}
Input 16: outline src/authoring/tools.rs mod[tests]/fn[additional_read_flow_searches_outlines_and_reads_a_rust_file]
- File:
src/authoring/tools.rs - Selector:
mod[tests]/fn[additional_read_flow_searches_outlines_and_reads_a_rust_file] - Kind:
fn src/authoring/tools.rs:1351–1495
// {test}`requirements.authoring.additional_read`
// {test}`requirements.authoring.github_reads`
// {test}`requirements.authoring.file_discovery`
// {test}`requirements.authoring.read_denial`
#[test]
fn additional_read_flow_searches_outlines_and_reads_a_rust_file() {
let root = project();
fs::write(
root.path().join("md/terms.md"),
":::{definition} value\n:phrase: value\nA useful value.\n:::\n",
)
.unwrap();
fs::write(
root.path().join("src/lib.rs"),
format!(
"// {}\nfn work() {{}}\n\nfn other() {{}}\n",
role("term", "terms.value")
),
)
.unwrap();
let mut sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
for arguments in [json!({}), json!({"issue": 7})] {
let error = dispatch(&sources, "github", &arguments).err().unwrap();
assert!(
error
.to_string()
.contains("github expects exactly an issue field"),
"{error}"
);
}
// GitHub reads return tool errors here, since unit tests never contact
// GitHub, and are never evidence inputs.
for (issue, message) in [
("example/app#1", "cannot read GitHub issue example/app#1"),
("example/app", "is not an issue reference"),
] {
let error = dispatch(&sources, "github", &json!({ "issue": issue }))
.err()
.unwrap();
assert!(error.to_string().contains(message), "{error}");
}
let directories = dispatch(&sources, "list_files", &json!({})).unwrap();
let directory = directories
.result
.as_array()
.unwrap()
.iter()
.find(|entry| entry["path"] == "src")
.unwrap();
assert_eq!(directory["kind"], "directory");
assert!(directories.inputs.is_empty());
// The listing finds the directory's file and records nothing.
let listing = dispatch(&sources, "list_files", &json!({"path":directory["path"]})).unwrap();
assert_eq!(listing.result, json!([{"path":"src/lib.rs","kind":"file"}]));
assert!(listing.inputs.is_empty());
// Searching the Rust file returns the innermost item containing the match.
let search = dispatch(
&sources,
"ripgrep",
&json!({"path":"src/lib.rs","pattern":"work","context":0}),
)
.unwrap();
// It only locates the item: nothing is recorded and no definitions
// accompany it.
assert!(search.inputs.is_empty());
assert_eq!(
search.result["matches"],
json!([{
"file": "src/lib.rs", "item": "fn[work]", "kind": "fn", "tag":"1",
"lines": [{"text": "fn work() {}", "matched": true}],
}])
);
// Outlining it lists its items without content and records nothing.
let outline = dispatch(&sources, "outline", &json!({"file":"src/lib.rs"})).unwrap();
assert!(outline.inputs.is_empty());
let items = outline
.result
.get("entries")
.unwrap_or(&outline.result)
.as_array()
.unwrap()
.iter()
.map(|entry| entry["item"].as_str().unwrap())
.collect::<Vec<_>>();
assert_eq!(items, ["fn[work]", "fn[other]"]);
assert!(!outline.result.to_string().contains("fn other()"));
// Reading one item by selector returns it with its terminology.
let item = dispatch(
&sources,
"habeas",
&json!({"file":"src/lib.rs","item":"fn[work]"}),
)
.unwrap();
assert_eq!(item.result["input"]["item"], "fn[work]");
assert!(
item.result["input"]["text"]
.as_array()
.unwrap()
.iter()
.any(|line| line == "fn work() {}")
);
assert_eq!(item.result["definitions"].as_array().unwrap().len(), 1);
assert_eq!(item.result["definitions"][0]["definition"], "terms.value");
assert!(
item.inputs
.iter()
.any(|input| input["definition"] == "terms.value")
);
assert_eq!(item.inputs.len(), 2);
sources.record_inputs(&item.inputs);
assert!(sources.recorded_inputs().contains(
&crate::inputs::outline_input(root.path(), "src/lib.rs", "fn[work]").unwrap()
));
assert_eq!(sources.recorded_inputs().len(), 2);
// A line range without line_end reads through EOF.
let eof = dispatch(
&sources,
"habeas",
&json!({"file":"src/lib.rs","line_start":2}),
)
.unwrap();
let covered = eof.result["inputs"]
.as_array()
.unwrap()
.iter()
.map(|input| input["item"].as_str().unwrap())
.collect::<Vec<_>>();
assert_eq!(covered, ["fn[work]", "fn[other]"]);
sources.record_inputs(&eof.inputs);
let recorded = sources.recorded_inputs();
for item in ["fn[work]", "fn[other]"] {
assert!(
recorded.contains(
&crate::inputs::outline_input(root.path(), "src/lib.rs", item).unwrap()
),
"{item} recorded: {recorded:?}"
);
}
assert!(
recorded
.iter()
.any(|input| input["definition"] == "terms.value"),
"terminology recorded: {recorded:?}"
);
}
Input 17: outline src/authoring/tools.rs mod[tests]/fn[generated_evidence_is_excluded_from_reads_search_and_discovery]
- File:
src/authoring/tools.rs - Selector:
mod[tests]/fn[generated_evidence_is_excluded_from_reads_search_and_discovery] - Kind:
fn src/authoring/tools.rs:1978–2115
// {test}`requirements.authoring.source_tools`
// {test}`requirements.authoring.file_discovery`
// {test}`requirements.authoring.text_search`
// {test}`requirements.authoring.structural_search`
// {test}`requirements.authoring.read_denial`
// {test}`requirements.authoring.tool_descriptions.special_cases`
#[test]
fn generated_evidence_is_excluded_from_reads_search_and_discovery() {
let root = project();
fs::create_dir(root.path().join("evidence")).unwrap();
fs::create_dir(root.path().join("src/evidence")).unwrap();
fs::write(
root.path().join("evidence/old.json"),
"needle in a previous judgment\n",
)
.unwrap();
fs::write(
root.path().join("evidence/generated.rs"),
"fn generated() {}\n",
)
.unwrap();
fs::write(root.path().join("source.txt"), "needle in source\n").unwrap();
fs::write(
root.path().join("src/evidence/source.txt"),
"needle in nested source\n",
)
.unwrap();
#[cfg(unix)]
{
std::os::unix::fs::symlink(
root.path().join("evidence"),
root.path().join("old-output"),
)
.unwrap();
std::os::unix::fs::symlink(
root.path().join("evidence/old.json"),
root.path().join("old.json"),
)
.unwrap();
}
git(root.path(), &["init", "--quiet"]);
git(root.path(), &["add", "."]);
let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
let search = dispatch(
&sources,
"ripgrep",
&json!({"pattern":"needle", "context":0}),
)
.unwrap();
let files = matched(&search)
.iter()
.map(|input| input["file"].as_str().unwrap())
.collect::<Vec<_>>();
assert_eq!(files, vec!["source.txt", "src/evidence/source.txt"]);
let structural = dispatch(
&sources,
"ast_grep",
&json!({"language":"rust","rule":{"rule":{"kind":"function_item"}}}),
)
.unwrap();
assert!(matched(&structural).is_empty(), "{:?}", structural.result);
assert!(
dispatch(
&sources,
"ast_grep",
&json!({"language":"rust","rule":{"rule":{"kind":"function_item"}},"path":"evidence"}),
)
.err()
.unwrap()
.to_string()
.contains("generated evidence")
);
let listing = dispatch(&sources, "list_files", &json!({})).unwrap();
assert!(listing.result.as_array().unwrap().iter().all(|entry| {
!["evidence", "old-output", "old.json"].contains(&entry["path"].as_str().unwrap())
}));
for path in ["evidence/old.json", "./evidence/old.json"] {
let error = dispatch(&sources, "habeas", &json!({"file":path, "line_start":1}))
.err()
.unwrap();
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
assert!(error.to_string().contains("evidence/old.json"), "{error}");
assert!(error.to_string().contains("generated evidence"), "{error}");
assert!(sources.recorded_inputs().is_empty());
}
for (name, arguments) in [
(
"habeas",
json!({"file":"evidence/generated.rs", "item":"fn[generated]"}),
),
("list_files", json!({"path":"evidence"})),
("ripgrep", json!({"path":"evidence", "pattern":"needle"})),
(
"ast_grep",
json!({"path":"evidence", "language":"rust","rule":{"rule":{"kind":"function_item"}}}),
),
] {
let error = dispatch(&sources, name, &arguments).err().unwrap();
let path = arguments["file"]
.as_str()
.or_else(|| arguments["path"].as_str())
.unwrap();
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
assert!(error.to_string().contains(path), "{error}");
assert!(error.to_string().contains("generated evidence"), "{error}");
assert!(sources.recorded_inputs().is_empty());
}
#[cfg(unix)]
{
for path in ["old.json", "old-output/old.json"] {
assert!(
dispatch(&sources, "habeas", &json!({"file":path, "line_start":1}))
.err()
.unwrap()
.to_string()
.contains("generated evidence")
);
assert!(
dispatch(
&sources,
"ripgrep",
&json!({"path":path, "pattern":"needle"})
)
.err()
.unwrap()
.to_string()
.contains("generated evidence")
);
}
assert!(
dispatch(&sources, "list_files", &json!({"path":"old-output"}))
.err()
.unwrap()
.to_string()
.contains("generated evidence")
);
}
}
Input 18: outline src/authoring/tools.rs mod[tests]/fn[operating_system_permission_failures_are_ordinary_read_failures]
- File:
src/authoring/tools.rs - Selector:
mod[tests]/fn[operating_system_permission_failures_are_ordinary_read_failures] - Kind:
fn src/authoring/tools.rs:2159–2203
// {test}`requirements.authoring.read_denial`
#[cfg(unix)]
#[test]
// {test}`requirements.authoring.text_search`
// {test}`requirements.authoring.structural_search`
fn operating_system_permission_failures_are_ordinary_read_failures() {
use std::os::unix::fs::PermissionsExt;
let root = project();
fs::create_dir(root.path().join("locked")).unwrap();
fs::write(root.path().join("locked.rs"), "fn locked() {}\n").unwrap();
let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
for path in ["locked", "locked.rs"] {
fs::set_permissions(root.path().join(path), fs::Permissions::from_mode(0o000)).unwrap();
}
let unreadable = fs::read(root.path().join("locked.rs")).is_err();
let results = [
dispatch(
&sources,
"ripgrep",
&json!({"path":"locked","pattern":"anything"}),
),
dispatch(
&sources,
"ast_grep",
&json!({"path":"locked","language":"rust","rule":{"rule":{"kind":"function_item"}}}),
),
dispatch(&sources, "list_files", &json!({"path": "locked"})),
dispatch(
&sources,
"habeas",
&json!({"file": "locked.rs", "line_start": 1}),
),
];
for path in ["locked", "locked.rs"] {
fs::set_permissions(root.path().join(path), fs::Permissions::from_mode(0o755)).unwrap();
}
if !unreadable {
// Permission bits do not restrict this user, e.g. root.
return;
}
for result in results {
let error = result.err().expect("the read fails");
assert_ne!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
}
}
Input 19: outline src/authoring/tools.rs mod[tests]/fn[untracked_diagnostics_name_git_add_and_an_allow_rule]
- File:
src/authoring/tools.rs - Selector:
mod[tests]/fn[untracked_diagnostics_name_git_add_and_an_allow_rule] - Kind:
fn src/authoring/tools.rs:2205–2243
// {test}`requirements.authoring.read_denial`
// {test}`requirements.authoring.read_denial.untracked`
// {test}`requirements.authoring.tool_descriptions.special_cases`
#[test]
fn untracked_diagnostics_name_git_add_and_an_allow_rule() {
let root = project();
fs::write(root.path().join("tracked.txt"), "tracked\n").unwrap();
git(root.path(), &["init", "--quiet"]);
git(root.path(), &["add", "."]);
fs::create_dir(root.path().join("untracked-dir")).unwrap();
fs::write(root.path().join("untracked-dir/file.rs"), "fn f() {}\n").unwrap();
fs::write(root.path().join("untracked.rs"), "fn g() {}\n").unwrap();
let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
for (name, arguments) in [
("habeas", json!({"file": "untracked.rs", "line_start": 1})),
("list_files", json!({"path": "untracked-dir"})),
] {
let error = dispatch(&sources, name, &arguments).err().unwrap();
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
let message = error.to_string();
assert!(message.contains("git add"), "{message}");
assert!(message.contains("habeas.toml allow rule"), "{message}");
let path = arguments["file"]
.as_str()
.or_else(|| arguments["path"].as_str())
.unwrap();
assert!(message.contains(path), "{message}");
}
// The harness neither stages nor permits the files itself.
let status = std::process::Command::new("git")
.args(["status", "--porcelain"])
.current_dir(root.path())
.output()
.unwrap();
let status = String::from_utf8(status.stdout).unwrap();
assert!(status.contains("?? untracked-dir/"), "{status}");
assert!(status.contains("?? untracked.rs"), "{status}");
assert!(!root.path().join("habeas.toml").exists());
}
Input 20: outline src/authoring/tools.rs mod[tests]/fn[requests_through_symlinks_leaving_the_project_are_denials]
- File:
src/authoring/tools.rs - Selector:
mod[tests]/fn[requests_through_symlinks_leaving_the_project_are_denials] - Kind:
fn src/authoring/tools.rs:2245–2283
// {test}`requirements.authoring.read_denial`
#[cfg(unix)]
#[test]
fn requests_through_symlinks_leaving_the_project_are_denials() {
let root = project();
let outside = tempfile::tempdir().unwrap();
fs::write(outside.path().join("secret.rs"), "fn secret() {}\n").unwrap();
std::os::unix::fs::symlink(outside.path(), root.path().join("outside")).unwrap();
std::os::unix::fs::symlink(
outside.path().join("secret.rs"),
root.path().join("outside.rs"),
)
.unwrap();
let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
for (name, arguments) in [
("habeas", json!({"file": "outside.rs", "line_start": 1})),
(
"habeas",
json!({"file": "outside.rs", "item": "fn[secret]"}),
),
("outline", json!({"file": "outside.rs"})),
(
"ripgrep",
json!({"path": "outside.rs", "pattern": "secret"}),
),
("list_files", json!({"path": "outside"})),
] {
let error = dispatch(&sources, name, &arguments).err().unwrap();
assert_eq!(
error.kind(),
io::ErrorKind::PermissionDenied,
"{name} {arguments}: {error}"
);
assert!(
error.to_string().contains("outside the project"),
"{name} {arguments}: {error}"
);
}
}
Input 21: outline src/authoring/tools.rs mod[tests]/fn[git_tools_allow_staged_and_dirty_sources_but_hide_untracked_files]
- File:
src/authoring/tools.rs - Selector:
mod[tests]/fn[git_tools_allow_staged_and_dirty_sources_but_hide_untracked_files] - Kind:
fn src/authoring/tools.rs:2285–2356
// {test}`requirements.authoring.source_tools`
// {test}`requirements.authoring.file_discovery`
// {test}`requirements.authoring.text_search`
// {test}`requirements.authoring.read_denial`
#[test]
fn git_tools_allow_staged_and_dirty_sources_but_hide_untracked_files() {
let root = project();
fs::create_dir(root.path().join("tracked-dir")).unwrap();
fs::write(root.path().join("tracked-dir/file.txt"), "original\n").unwrap();
fs::write(root.path().join("staged.txt"), "needle staged\n").unwrap();
git(root.path(), &["init", "--quiet"]);
git(root.path(), &["add", "."]);
fs::write(root.path().join("tracked-dir/file.txt"), "needle dirty\n").unwrap();
fs::create_dir(root.path().join("untracked-dir")).unwrap();
fs::write(
root.path().join("untracked-dir/file.txt"),
"needle hidden\n",
)
.unwrap();
fs::write(root.path().join("untracked.rs"), "fn needle() {}\n").unwrap();
let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
let listing = dispatch(&sources, "list_files", &json!({})).unwrap();
assert_eq!(
listing
.result
.get("entries")
.unwrap_or(&listing.result)
.as_array()
.unwrap()
.iter()
.map(|entry| entry["path"].as_str().unwrap())
.collect::<Vec<_>>(),
vec!["Cargo.toml", "book.toml", "md", "staged.txt", "tracked-dir"]
);
for (path, text) in [
("staged.txt", "needle staged"),
("tracked-dir/file.txt", "needle dirty"),
] {
let read = dispatch(&sources, "habeas", &json!({"file":path, "line_start":1})).unwrap();
assert_eq!(read.result["inputs"][0]["text"], json!([text]));
}
let search = dispatch(&sources, "ripgrep", &json!({"pattern":"needle"})).unwrap();
assert_eq!(
matched(&search)
.iter()
.map(|input| input["file"].as_str().unwrap())
.collect::<Vec<_>>(),
vec!["staged.txt", "tracked-dir/file.txt"]
);
for arguments in [
json!({"file":"untracked.rs", "line_start":1}),
json!({"file":"untracked.rs", "line_start":1, "line_end":1}),
json!({"file":"untracked.rs", "item":"fn[needle]"}),
] {
let error = dispatch(&sources, "habeas", &arguments).err().unwrap();
assert!(error.to_string().contains("git add"), "{error}");
}
let error = dispatch(&sources, "outline", &json!({"file":"untracked.rs"}))
.err()
.unwrap();
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
assert!(error.to_string().contains("git add"), "{error}");
assert!(dispatch(&sources, "list_files", &json!({"path":"untracked-dir"})).is_err());
assert!(
dispatch(
&sources,
"ripgrep",
&json!({"path":"untracked.rs", "pattern":"needle"})
)
.is_err()
);
}
Input 22: outline src/authoring/tools.rs mod[tests]/fn[git_symlink_reads_require_both_the_alias_and_target_to_be_tracked]
- File:
src/authoring/tools.rs - Selector:
mod[tests]/fn[git_symlink_reads_require_both_the_alias_and_target_to_be_tracked] - Kind:
fn src/authoring/tools.rs:2358–2430
// {test}`requirements.authoring.source_tools`
// {test}`requirements.authoring.file_discovery`
// {test}`requirements.authoring.text_search`
// {test}`requirements.authoring.read_denial`
#[cfg(unix)]
#[test]
fn git_symlink_reads_require_both_the_alias_and_target_to_be_tracked() {
let root = project();
fs::write(root.path().join("tracked.txt"), "needle allowed\n").unwrap();
fs::write(root.path().join("untracked.txt"), "needle hidden\n").unwrap();
for (alias, target) in [
("tracked-alias.txt", "tracked.txt"),
("untracked-target.txt", "untracked.txt"),
("untracked-alias.txt", "tracked.txt"),
] {
std::os::unix::fs::symlink(target, root.path().join(alias)).unwrap();
}
git(root.path(), &["init", "--quiet"]);
git(
root.path(),
&[
"add",
"Cargo.toml",
"book.toml",
"md",
"tracked.txt",
"tracked-alias.txt",
"untracked-target.txt",
],
);
let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
let allowed = dispatch(
&sources,
"habeas",
&json!({"file":"tracked-alias.txt", "line_start":1}),
)
.unwrap();
assert_eq!(
allowed.result["inputs"][0]["text"],
json!(["needle allowed"])
);
for alias in ["untracked-target.txt", "untracked-alias.txt"] {
assert!(
dispatch(&sources, "habeas", &json!({"file":alias, "line_start":1}))
.err()
.unwrap()
.to_string()
.contains("git add")
);
assert!(
dispatch(
&sources,
"ripgrep",
&json!({"path":alias, "pattern":"needle"})
)
.is_err()
);
}
let listing = dispatch(&sources, "list_files", &json!({})).unwrap();
let paths = listing
.result
.get("entries")
.unwrap_or(&listing.result)
.as_array()
.unwrap()
.iter()
.map(|entry| entry["path"].as_str().unwrap())
.collect::<Vec<_>>();
assert!(paths.contains(&"tracked-alias.txt"));
assert!(!paths.contains(&"untracked-target.txt"));
assert!(!paths.contains(&"untracked-alias.txt"));
assert!(!paths.contains(&"untracked.txt"));
}
Input 23: outline src/authoring/tools.rs mod[tests]/fn[allowed_ignored_and_external_sources_are_discoverable_but_disallowed_descendants_are_not]
- File:
src/authoring/tools.rs - Selector:
mod[tests]/fn[allowed_ignored_and_external_sources_are_discoverable_but_disallowed_descendants_are_not] - Kind:
fn src/authoring/tools.rs:2432–2566
// {test}`requirements.configuration.evidence_paths`
// {test}`requirements.authoring.source_tools`
// {test}`requirements.authoring.file_discovery`
// {test}`requirements.authoring.text_search`
// {test}`requirements.authoring.read_denial`
// {test}`requirements.authoring.structural_search`
#[test]
fn allowed_ignored_and_external_sources_are_discoverable_but_disallowed_descendants_are_not() {
let root = project();
let external = tempfile::tempdir().unwrap();
fs::create_dir_all(root.path().join("generated/private")).unwrap();
fs::write(
root.path().join("generated/visible.txt"),
"needle allowed\n",
)
.unwrap();
fs::write(
root.path().join("generated/private/hidden.txt"),
"needle denied\n",
)
.unwrap();
fs::write(external.path().join("outside.txt"), "needle external\n").unwrap();
fs::write(external.path().join("outside.rs"), "fn external() {}\n").unwrap();
fs::write(
root.path().join("generated/visible.rs"),
"fn visible() {}\n",
)
.unwrap();
fs::write(
root.path().join("generated/private/denied.rs"),
"fn denied() {}\n",
)
.unwrap();
fs::write(root.path().join(".hidden.rs"), "fn hidden() {}\n").unwrap();
fs::write(root.path().join(".gitignore"), "generated/\n").unwrap();
git(root.path(), &["init", "--quiet"]);
git(root.path(), &["add", "."]);
let external_toml = toml::Value::String(external.path().display().to_string());
fs::write(root.path().join("habeas.toml"), format!(
"version = 1\n[evidence]\nallow = ['generated', '.hidden.rs', {external_toml}]\ndisallow = ['generated/private']\n"
)).unwrap();
let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
let listing = dispatch(&sources, "list_files", &json!({})).unwrap();
let paths = listing
.result
.get("entries")
.unwrap_or(&listing.result)
.as_array()
.unwrap()
.iter()
.map(|entry| entry["path"].as_str().unwrap())
.collect::<Vec<_>>();
assert!(paths.contains(&"generated"));
assert!(paths.contains(&external.path().to_str().unwrap()));
let generated = dispatch(&sources, "list_files", &json!({"path":"generated"})).unwrap();
assert_eq!(
generated.result,
json!([
{"path":"generated/visible.rs", "kind":"file"},
{"path":"generated/visible.txt", "kind":"file"}
])
);
assert!(generated.inputs.is_empty());
let external_listing =
dispatch(&sources, "list_files", &json!({"path":external.path()})).unwrap();
assert_eq!(
external_listing.result,
json!([
{"path":external.path().join("outside.rs"),"kind":"file"},
{"path":external.path().join("outside.txt"),"kind":"file"}
])
);
assert!(external_listing.inputs.is_empty());
let structural = dispatch(
&sources,
"ast_grep",
&json!({"language":"rust","rule":{"rule":{"kind":"function_item"}}}),
)
.unwrap();
let structural_files = matched(&structural)
.iter()
.map(|entry| entry["file"].as_str().unwrap())
.collect::<Vec<_>>();
for expected in [
".hidden.rs",
"generated/visible.rs",
external.path().join("outside.rs").to_str().unwrap(),
] {
assert!(structural_files.contains(&expected), "{structural_files:?}");
}
assert!(!structural_files.contains(&"generated/private/denied.rs"));
assert!(structural.inputs.is_empty());
let search = dispatch(
&sources,
"ripgrep",
&json!({"pattern":"needle", "context":0}),
)
.unwrap();
assert_eq!(matched(&search).len(), 2);
assert!(
matched(&search)
.iter()
.any(|input| input["file"] == "generated/visible.txt")
);
assert!(matched(&search).iter().any(|input| input["file"] == external.path().join("outside.txt").to_str().unwrap()));
let read = dispatch(
&sources,
"habeas",
&json!({"file":external.path().join("outside.txt"), "line_start":1}),
)
.unwrap();
assert_eq!(read.result["inputs"][0]["text"], json!(["needle external"]));
for (name, args) in [
(
"habeas",
json!({"file":"generated/private/hidden.txt", "line_start":1}),
),
("list_files", json!({"path":"generated/private"})),
(
"ripgrep",
json!({"path":"generated/private", "pattern":"needle"}),
),
(
"ast_grep",
json!({"path":"generated/private","language":"rust","rule":{"rule":{"kind":"function_item"}}}),
),
] {
assert_eq!(
dispatch(&sources, name, &args).err().unwrap().kind(),
io::ErrorKind::PermissionDenied
);
}
}
Input 24: outline src/authoring/tools.rs mod[tests]/fn[cargo_output_is_discovered_and_read_without_building_or_allowing_other_target_files]
- File:
src/authoring/tools.rs - Selector:
mod[tests]/fn[cargo_output_is_discovered_and_read_without_building_or_allowing_other_target_files] - Kind:
fn src/authoring/tools.rs:2568–2703
// {test}`requirements.authoring.generated_inputs`
// {test}`requirements.authoring.file_discovery`
// {test}`requirements.authoring.text_search`
// {test}`requirements.authoring.source_tools`
// {test}`requirements.configuration.evidence_paths`
// {test}`requirements.authoring.read_denial`
// {test}`requirements.authoring.read_denial.build_output`
// {test}`requirements.authoring.structural_search`
#[test]
fn cargo_output_is_discovered_and_read_without_building_or_allowing_other_target_files() {
let root = project();
fs::write(root.path().join("src/lib.rs"), "pub fn ready() {}\n").unwrap();
fs::write(
root.path().join("Cargo.lock"),
"version = 4\n\n[[package]]\nname = 'fixture'\nversion = '0.1.0'\n",
)
.unwrap();
fs::write(root.path().join(".gitignore"), "target/\n").unwrap();
git(root.path(), &["init", "--quiet"]);
git(root.path(), &["add", "."]);
let unbuilt = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
assert!(
dispatch(
&unbuilt,
"habeas",
&json!({"file":"src/lib.rs", "line_start":1})
)
.is_ok()
);
assert!(!root.path().join("target").exists());
let out = root.path().join("target/debug/build/fixture-hash/out");
fs::create_dir_all(&out).unwrap();
fs::write(out.join("generated.rs"), "pub fn generated_needle() {}\n").unwrap();
fs::write(
out.parent().unwrap().join("root-output"),
out.to_str().unwrap(),
)
.unwrap();
let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
let listing = dispatch(&sources, "list_files", &json!({})).unwrap();
assert!(
listing
.result
.get("entries")
.unwrap_or(&listing.result)
.as_array()
.unwrap()
.iter()
.any(|entry| entry["path"] == "target/debug/build/fixture-hash/out")
);
let search = dispatch(&sources, "ripgrep", &json!({"pattern":"generated_needle"})).unwrap();
let generated = dispatch(
&sources,
"list_files",
&json!({"path":"target/debug/build/fixture-hash/out"}),
)
.unwrap();
assert_eq!(
generated.result,
json!([{"path":"target/debug/build/fixture-hash/out/generated.rs","kind":"file"}])
);
assert!(generated.inputs.is_empty());
assert_eq!(matched(&search).len(), 1);
let structural_arguments =
json!({"language":"rust","rule":{"rule":{"pattern":"pub fn generated_needle() {}"}}});
let structural = dispatch(&sources, "ast_grep", &structural_arguments).unwrap();
assert_eq!(
found(&structural),
["target/debug/build/fixture-hash/out/generated.rs#fn[generated_needle]"]
);
assert!(structural.inputs.is_empty());
let read = dispatch(&sources, "habeas", &json!({"file":"target/debug/build/fixture-hash/out/generated.rs", "item":"fn[generated_needle]"})).unwrap();
assert_eq!(
read.result["input"]["text"],
json!(["pub fn generated_needle() {}"])
);
// Other build output under target is an ordinary read failure.
let error = dispatch(
&sources,
"habeas",
&json!({"file":"target/debug/build/fixture-hash/root-output", "line_start":1}),
)
.err()
.unwrap();
assert_ne!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
assert!(error.to_string().contains("holds build output"), "{error}");
fs::write(
root.path().join("habeas.toml"),
"version = 1\n[evidence]\ndisallow = ['target/debug/build/fixture-hash/out']\n",
)
.unwrap();
let denied = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
let listing = dispatch(&denied, "list_files", &json!({})).unwrap();
assert!(
!listing
.result
.get("entries")
.unwrap_or(&listing.result)
.as_array()
.unwrap()
.iter()
.any(|entry| entry["path"] == "target/debug/build/fixture-hash/out")
);
assert!(
matched(&dispatch(&denied, "ripgrep", &json!({"pattern":"generated_needle"})).unwrap())
.is_empty()
);
assert!(matched(&dispatch(&denied, "ast_grep", &structural_arguments).unwrap()).is_empty());
for (name, arguments) in [
(
"habeas",
json!({"file":"target/debug/build/fixture-hash/out/generated.rs", "line_start":1}),
),
(
"list_files",
json!({"path":"target/debug/build/fixture-hash/out"}),
),
(
"ripgrep",
json!({"path":"target/debug/build/fixture-hash/out", "pattern":"generated_needle"}),
),
(
"ast_grep",
json!({"path":"target/debug/build/fixture-hash/out","language":"rust","rule":{"rule":{"kind":"function_item"}}}),
),
] {
let error = dispatch(&denied, name, &arguments).err().unwrap();
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
assert!(error.to_string().contains("disallowed"), "{error}");
let path = arguments["file"]
.as_str()
.or_else(|| arguments["path"].as_str())
.unwrap();
assert!(error.to_string().contains(path), "{error}");
}
}
Input 25: outline src/authoring/tools.rs mod[tests]/fn[references_list_names_and_flattened_sites_without_recording_inputs]
- File:
src/authoring/tools.rs - Selector:
mod[tests]/fn[references_list_names_and_flattened_sites_without_recording_inputs] - Kind:
fn src/authoring/tools.rs:2732–2899
// {test}`requirements.authoring.reference_index`
// {test}`requirements.references.definition_globs`
// {test}`requirements.authoring.no_line_numbers`
// {test}`requirements.authoring.read_denial`
#[test]
// {test}`requirements.references.authoring_inputs`
// {test}`requirements.authoring.read_denial`
fn references_list_names_and_flattened_sites_without_recording_inputs() {
let root = project();
fs::write(
root.path().join("md/requirements.md"),
format!(
":::{{req}} ready\nThe project MUST be ready.\n:::\n\n:::{{req}} other\nOther MUST hold.\n:::\n\n:::{{example}} case\nA ready case. {}\n:::\n\n:::{{definition}} word\n:phrase: word\n:impl: src/lib.rs#fn[work]\nA vocabulary term.\n:::\n",
role("cite", "requirements.ready")
),
)
.unwrap();
fs::write(
root.path().join("src/lib.rs"),
format!(
"// {}\nfn zeta() {{}}\n\n// {}\nfn work() {{\n // {}\n // {}\n}}\n",
role("test", "requirements.ready"),
role("impl", "requirements.ready"),
role("cite", "requirements.other"),
role("term", "requirements.word"),
),
)
.unwrap();
fs::create_dir_all(root.path().join("private")).unwrap();
fs::write(
root.path().join("private/notes.md"),
format!("{}\n", role("cite", "requirements.ready")),
)
.unwrap();
fs::write(
root.path().join("habeas.toml"),
"version = 1\n\n[evidence]\ndisallow = [\"private\"]\n",
)
.unwrap();
let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
let all = dispatch(&sources, "references", &json!({})).unwrap();
assert_eq!(
all.result,
json!({"definitions": [
{"name": "requirements.case", "kind": "example"},
{"name": "requirements.other", "kind": "requirement"},
{"name": "requirements.ready", "kind": "requirement"},
], "sites": []})
);
assert!(all.inputs.is_empty());
let ready = dispatch(
&sources,
"references",
&json!({"selection": "requirements.ready"}),
)
.unwrap();
let mut result = ready.result.clone();
let markdown = result["sites"][0]["item"].take();
assert!(
markdown.as_str().unwrap().starts_with("section@"),
"{markdown}"
);
assert_eq!(
result,
json!({"definitions": [{"name": "requirements.ready", "kind": "requirement"}], "sites": [
{"name": "requirements.ready", "role": "cite", "file": "md/requirements.md", "item": null},
{"name": "requirements.ready", "role": "test", "file": "src/lib.rs", "item": "fn[zeta]"},
{"name": "requirements.ready", "role": "impl", "file": "src/lib.rs", "item": "fn[work]"},
]})
);
assert!(ready.inputs.is_empty());
let implementations = dispatch(
&sources,
"references",
&json!({"selection":"requirements.ready", "roles":["impl", "impl"]}),
)
.unwrap();
assert_eq!(
implementations.result,
json!({"definitions":[{"name":"requirements.ready","kind":"requirement"}],
"sites":[{"name":"requirements.ready","role":"impl","file":"src/lib.rs","item":"fn[work]"}]})
);
assert!(implementations.inputs.is_empty());
let names = dispatch(
&sources,
"references",
&json!({"selection":"requirements.ready", "roles":[]}),
)
.unwrap();
assert_eq!(names.result["definitions"], ready.result["definitions"]);
assert_eq!(names.result["sites"], json!([]));
assert!(names.inputs.is_empty());
assert_eq!(
dispatch(&sources, "references", &json!({"roles":["impl"]}))
.unwrap()
.result,
all.result
);
for roles in [json!(null), json!("impl"), json!(["fixme"]), json!([1])] {
let error = dispatch(&sources, "references", &json!({"roles":roles}))
.err()
.unwrap();
assert!(error.to_string().contains("role"), "{roles}: {error}");
}
let flattened = dispatch(
&sources,
"references",
&json!({"selection": "requirements.*"}),
)
.unwrap();
let sites = flattened.result["sites"].as_array().unwrap();
assert_eq!(flattened.result["definitions"], all.result["definitions"]);
assert_eq!(sites.len(), 4);
assert_eq!(sites[0]["name"], "requirements.other");
assert_eq!(sites[0]["item"], "fn[work]");
assert!(flattened.inputs.is_empty());
// A fenced reference in a comment run is a site of the node the run
// belongs to; a `{fixme}` is not a site, nor is a fence that never
// closes.
fs::write(
root.path().join("src/fenced.rs"),
format!(
"// :::{} requirements.other\n// Commentary.\n// :::\nfn fenced() {{}}\n\n// :::{} requirements.other\n// Tracked by example/queue#1.\n// :::\nfn gap() {{}}\n\n// :::{} requirements.other\n// never closed\n\nfn open() {{}}\n",
"{impl}", "{fixme}", "{cite}"
),
)
.unwrap();
let other = dispatch(
&sources,
"references",
&json!({"selection": "requirements.other"}),
)
.unwrap();
assert_eq!(
other.result["sites"],
json!([
{"name": "requirements.other", "role": "impl", "file": "src/fenced.rs", "item": "fn[fenced]"},
{"name": "requirements.other", "role": "cite", "file": "src/lib.rs", "item": "fn[work]"},
])
);
fs::remove_file(root.path().join("src/fenced.rs")).unwrap();
for selection in ["requirements.missing", "requirements.word", "bad name", ""] {
assert!(
dispatch(&sources, "references", &json!({"selection": selection})).is_err(),
"accepted {selection:?}"
);
}
let error = dispatch(&sources, "references", &json!({"selection": 1}))
.err()
.unwrap();
assert!(
error.to_string().contains("selection must be a string"),
"{error}"
);
assert!(
dispatch(
&sources,
"references",
&json!({"name": "requirements.ready"})
)
.is_err()
);
}
Input 26: outline src/authoring/tools.rs mod[tests]/fn[unpermitted_requests_outside_the_project_are_recoverable_tool_errors]
- File:
src/authoring/tools.rs - Selector:
mod[tests]/fn[unpermitted_requests_outside_the_project_are_recoverable_tool_errors] - Kind:
fn src/authoring/tools.rs:3086–3144
// {test}`requirements.authoring.read_denial`
// {test}`requirements.authoring.source_tools`
// {test}`requirements.authoring.file_discovery`
// {test}`requirements.authoring.text_search`
// {test}`requirements.authoring.outline_tool`
// {test}`requirements.authoring.tool_descriptions.special_cases`
#[test]
fn unpermitted_requests_outside_the_project_are_recoverable_tool_errors() {
let root = project();
let external = tempfile::tempdir().unwrap();
fs::write(external.path().join("lib.rs"), "fn external() {}\n").unwrap();
let file = external.path().join("lib.rs");
let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
let requests = [
("habeas", json!({"file": file, "line_start": 1})),
("habeas", json!({"file": file, "item": "fn[external]"})),
("list_files", json!({"path": external.path()})),
("outline", json!({"file": file})),
(
"ripgrep",
json!({"path": external.path(), "pattern": "external"}),
),
];
for (name, arguments) in &requests {
let error = dispatch(&sources, name, arguments).err().unwrap();
assert_ne!(
error.kind(),
io::ErrorKind::PermissionDenied,
"{name}: {error}"
);
assert!(error.to_string().contains("outside the project"), "{error}");
}
assert!(sources.recorded_inputs().is_empty());
// A matching disallow still aborts, as do in-project denials.
fs::write(
root.path().join("habeas.toml"),
format!(
"version = 1\n[evidence]\ndisallow = [{:?}]\n",
external.path().to_str().unwrap()
),
)
.unwrap();
fs::create_dir_all(root.path().join("evidence")).unwrap();
fs::write(root.path().join("evidence/old.json"), "{}\n").unwrap();
let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
for (name, arguments) in &requests[..1] {
let error = dispatch(&sources, name, arguments).err().unwrap();
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
}
let error = dispatch(
&sources,
"habeas",
&json!({"file": "evidence/old.json", "item": ""}),
)
.err()
.unwrap();
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
}
Input 27: outline src/authoring/tools.rs mod[tests]/fn[requests_for_book_or_target_output_are_ordinary_read_failures]
- File:
src/authoring/tools.rs - Selector:
mod[tests]/fn[requests_for_book_or_target_output_are_ordinary_read_failures] - Kind:
fn src/authoring/tools.rs:3146–3203
// {test}`requirements.authoring.read_denial`
// {test}`requirements.authoring.read_denial.build_output`
// {test}`requirements.authoring.tool_descriptions.special_cases`
#[test]
fn requests_for_book_or_target_output_are_ordinary_read_failures() {
let root = project();
for (book, built) in [("", "book"), ("[build]\nbuild-dir = 'site'\n", "site")] {
fs::write(
root.path().join("book.toml"),
format!("[book]\nsrc = 'md'\n{book}"),
)
.unwrap();
for directory in [built, "target"] {
fs::create_dir_all(root.path().join(directory).join("nested")).unwrap();
fs::write(
root.path().join(directory).join("nested/page.html"),
"fn built_needle() {}\n",
)
.unwrap();
}
let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
for directory in [built, "target"] {
let file = format!("{directory}/nested/page.html");
for (name, arguments) in [
("habeas", json!({"file": file, "line_start": 1})),
("habeas", json!({"file": file, "item": ""})),
("outline", json!({"file": file})),
("list_files", json!({"path": directory})),
("ripgrep", json!({"pattern": "needle", "path": directory})),
] {
let error = dispatch(&sources, name, &arguments).err().unwrap();
assert_ne!(
error.kind(),
io::ErrorKind::PermissionDenied,
"{name} {arguments}: {error}"
);
assert!(
error.to_string().contains("holds build output")
&& error.to_string().contains(
"the sources it is built from are elsewhere in the project"
),
"{name} {arguments}: {error}"
);
}
}
}
// With a build-dir set, `book` is an ordinary project directory.
fs::write(root.path().join("book/source.txt"), "plain\n").unwrap();
let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
assert!(
dispatch(
&sources,
"habeas",
&json!({"file":"book/source.txt","line_start":1})
)
.is_ok()
);
}
Input 28: outline src/authoring/tools.rs mod[tests]/fn[mandatory_inputs_outside_the_project_still_abort]
- File:
src/authoring/tools.rs - Selector:
mod[tests]/fn[mandatory_inputs_outside_the_project_still_abort] - Kind:
fn src/authoring/tools.rs:3205–3225
// {test}`requirements.authoring.read_denial`
// {test}`requirements.authoring.mandatory_inputs`
#[test]
fn mandatory_inputs_outside_the_project_still_abort() {
let root = project();
let external = tempfile::tempdir().unwrap();
fs::write(external.path().join("skill.md"), "# Skill\n").unwrap();
fs::write(
root.path().join("md/requirements.md"),
format!(
":::{{req}} ready\n:impl: {}\nThe project MUST be ready.\n:::\n",
external.path().join("skill.md").display()
),
)
.unwrap();
let error = AssessmentSources::prepare(root.path(), "requirements.ready")
.err()
.unwrap();
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
assert!(error.to_string().contains("outside the project"), "{error}");
}
Input 29: outline src/authoring/tools.rs mod[tests]/fn[outline_lists_nested_nodes_without_text_or_inputs]
- File:
src/authoring/tools.rs - Selector:
mod[tests]/fn[outline_lists_nested_nodes_without_text_or_inputs] - Kind:
fn src/authoring/tools.rs:3360–3420
// {test}`requirements.authoring.outline_tool`
// {test}`requirements.references.outlines`
// {test}`requirements.authoring.no_line_numbers`
// {test}`requirements.authoring.read_denial`
#[test]
fn outline_lists_nested_nodes_without_text_or_inputs() {
let root = project();
fs::write(
root.path().join("src/lib.rs"),
"/// Docs.\nstruct Thing;\n\nimpl Thing {\n fn run(&self) {}\n}\n",
)
.unwrap();
fs::write(root.path().join("notes.txt"), "alpha\n\nbeta\n").unwrap();
let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
let outline = dispatch(&sources, "outline", &json!({"file":"src/lib.rs"})).unwrap();
assert!(outline.inputs.is_empty());
assert_eq!(
outline.result,
json!([
{"item": "struct[Thing]", "kind": "struct", "name": "Thing", "children": []},
{"item": "impl[Thing]", "kind": "impl", "name": "Thing", "children": [
{"item": "impl[Thing]/fn[run]", "kind": "fn", "name": "run", "children": []},
]},
])
);
assert!(!outline.result.to_string().contains("Docs"));
let plain = dispatch(&sources, "outline", &json!({"file":"notes.txt"})).unwrap();
let entries = plain.result.as_array().unwrap();
assert_eq!(entries.len(), 2);
assert!(entries.iter().all(|entry| entry["kind"] == "line"
&& entry["name"].is_null()
&& entry["item"].as_str().unwrap().starts_with("line@")));
assert!(entries[1].get("line_start").is_none());
for (arguments, message) in [
(json!({"file":"missing.rs"}), "missing.rs"),
(json!({}), "file"),
(json!({"file":1}), "file"),
(json!({"file":"src/lib.rs", "extra":true}), "extra"),
] {
let error = dispatch(&sources, "outline", &arguments).err().unwrap();
assert!(error.to_string().contains(message), "{arguments}: {error}");
}
let error = dispatch(&sources, "outline", &json!({})).err().unwrap();
assert!(
error.to_string().contains("file must be a string"),
"{error}"
);
fs::write(
root.path().join("habeas.toml"),
"version = 1\n[evidence]\ndisallow = ['notes.txt']\n",
)
.unwrap();
let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
let error = dispatch(&sources, "outline", &json!({"file":"notes.txt"}))
.err()
.unwrap();
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
assert!(error.to_string().contains("notes.txt"), "{error}");
assert!(error.to_string().contains("disallowed"), "{error}");
}
Input 30: outline src/authoring/tools.rs mod[tests]/fn[search_records_nothing_clamps_at_eof_and_reports_failures]
- File:
src/authoring/tools.rs - Selector:
mod[tests]/fn[search_records_nothing_clamps_at_eof_and_reports_failures] - Kind:
fn src/authoring/tools.rs:3861–3951
// {test}`requirements.authoring.text_search`
// {test}`requirements.authoring.read_denial`
// {test}`requirements.authoring.additional_read`
#[test]
fn search_records_nothing_clamps_at_eof_and_reports_failures() {
let root = project();
fs::write(
root.path().join("md/terms.md"),
":::{definition} value\n:phrase: value\nA useful value.\n:::\n",
)
.unwrap();
fs::write(
root.path().join("src/lib.rs"),
format!(
"fn first() {{}}\n\n// {}\nfn needle() {{}}\n",
role("term", "terms.value")
),
)
.unwrap();
// An allowed hidden directory is searched; an unallowed one is not.
fs::create_dir_all(root.path().join(".generated")).unwrap();
fs::write(root.path().join(".generated/out.txt"), "needle allowed\n").unwrap();
fs::create_dir_all(root.path().join(".other")).unwrap();
fs::write(root.path().join(".other/out.txt"), "needle hidden\n").unwrap();
fs::write(
root.path().join("habeas.toml"),
"version = 1\n[evidence]\nallow = ['.generated']\n",
)
.unwrap();
let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
let search = dispatch(
&sources,
"ripgrep",
&json!({"pattern":"fn needle","path":"src","context":5}),
)
.unwrap();
// Context includes the attached comment and stops at the item boundary.
assert_eq!(
matched(&search),
&vec![
json!({"file": "src/lib.rs", "item": "fn[needle]", "kind": "fn", "tag":"1",
"lines": [
{"text": "// {term}`terms.value`", "matched": false},
{"text": "fn needle() {}", "matched": true},
]})
]
);
// The terminology the node uses is neither supplied nor recorded.
assert!(search.result.get("definitions").is_none());
assert!(sources.recorded_inputs().is_empty());
let hidden = dispatch(
&sources,
"ripgrep",
&json!({"pattern":"needle (allowed|hidden)","context":0}),
)
.unwrap();
let files = matched(&hidden)
.iter()
.map(|input| input["file"].as_str().unwrap())
.collect::<Vec<_>>();
assert_eq!(files, [".generated/out.txt"]);
// Invalid arguments are explanatory tool errors.
for (arguments, message) in [
(json!({}), "pattern must be a string"),
(json!({"pattern": 1}), "pattern must be a string"),
(json!({"pattern":"x","path":1}), "path must be a string"),
(
json!({"pattern":"x","context":1.5}),
"context must be a nonnegative integer",
),
(
json!({"pattern":"x","extra":true}),
"unexpected tool argument \"extra\"",
),
(json!({"pattern":"("}), "invalid ripgrep pattern"),
] {
let error = dispatch(&sources, "ripgrep", &arguments).err().unwrap();
assert!(error.to_string().contains(message), "{arguments}: {error}");
}
// A matched file that cannot be parsed fails the search with an
// explanatory error rather than silently dropping the match.
fs::write(root.path().join("src/broken.rs"), "fn needle( {\n").unwrap();
let error = dispatch(
&sources,
"ripgrep",
&json!({"pattern":"fn needle","path":"src"}),
)
.err()
.unwrap();
assert!(error.to_string().contains("syntax error"), "{error}");
}
Input 31: outline src/authoring/tools.rs mod[tests]/fn[listings_and_searches_name_untracked_files_without_their_contents]
- File:
src/authoring/tools.rs - Selector:
mod[tests]/fn[listings_and_searches_name_untracked_files_without_their_contents] - Kind:
fn src/authoring/tools.rs:4220–4317
// {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());
}
}
}
Input 32: outline src/authoring/tools.rs mod[tests]/fn[failed_listings_return_explanatory_tool_errors]
- File:
src/authoring/tools.rs - Selector:
mod[tests]/fn[failed_listings_return_explanatory_tool_errors] - Kind:
fn src/authoring/tools.rs:4379–4398
// {test}`requirements.authoring.file_discovery`
// {test}`requirements.authoring.read_denial`
#[test]
fn failed_listings_return_explanatory_tool_errors() {
let root = project();
fs::write(root.path().join("src/lib.rs"), "fn work() {}\n").unwrap();
let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
for (arguments, message) in [
(json!({"path": "missing"}), "cannot"),
(json!({"path": "src/lib.rs"}), "cannot list"),
(json!({"path": 3}), "path"),
(json!({"path": ".", "extra": true}), "extra"),
] {
let error = dispatch(&sources, "list_files", &arguments)
.err()
.unwrap_or_else(|| panic!("{arguments} fails"));
assert_ne!(error.kind(), io::ErrorKind::PermissionDenied, "{arguments}");
assert!(error.to_string().contains(message), "{arguments}: {error}");
}
}
Input 33: outline src/authoring/tools.rs mod[tests]/fn[ast_grep_returns_innermost_nodes_of_the_language_and_reports_failures]
- File:
src/authoring/tools.rs - Selector:
mod[tests]/fn[ast_grep_returns_innermost_nodes_of_the_language_and_reports_failures] - Kind:
fn src/authoring/tools.rs:4678–4825
// {test}`requirements.authoring.structural_search`
// {test}`requirements.references.outline_comments`
// {test}`requirements.authoring.redaction`
// {test}`requirements.authoring.read_denial`
#[test]
fn ast_grep_returns_innermost_nodes_of_the_language_and_reports_failures() {
let root = project();
fs::write(
root.path().join("md/terms.md"),
":::{definition} value\n:phrase: value\nA useful value.\n:::\n",
)
.unwrap();
let token = ["gh", "p_", "abcdefghijklmnopqrstuvwxyz0123456789"].concat();
fs::write(
root.path().join("src/lib.rs"),
format!(
"// {}\nfn first() {{\n let x = value.unwrap();\n}}\n\n/// Calls unwrap in docs.\nfn second() {{\n other(\"{token}\").unwrap();\n}}\n\nmod inner {{\n fn third() {{\n a.unwrap();\n b.unwrap();\n }}\n}}\n",
role("term", "terms.value")
),
)
.unwrap();
fs::write(
root.path().join("src/a.rs"),
"fn a() {\n z.unwrap();\n}\n",
)
.unwrap();
fs::write(root.path().join("src/tool.py"), "value.unwrap()\n").unwrap();
let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
let rust = |rule: Value, path: &str| {
dispatch(
&sources,
"ast_grep",
&json!({"language":"rust","rule":rule,"path":path}),
)
};
let search = rust(json!({"rule":{"pattern":"$X.unwrap()"}}), ".").unwrap();
// Only Rust files are searched, ordered by path and then line, and
// each node once.
assert_eq!(
found(&search),
[
"src/a.rs#fn[a]",
"src/lib.rs#fn[first]",
"src/lib.rs#fn[second]",
"src/lib.rs#mod[inner]/fn[third]"
]
);
// Each entry shows the matched lines, redacted; no terminology is
// supplied.
let second = &matched(&search)[2]["lines"];
assert_eq!(second[0]["matched"], true);
assert!(second.to_string().contains("[REDACTED:"), "{second}");
assert!(!second.to_string().contains(&token), "{second}");
assert_eq!(
matched(&search)[3]["lines"],
json!([
{"text": " a.unwrap();", "matched": true},
{"text": " b.unwrap();", "matched": true},
])
);
assert!(search.result.get("definitions").is_none());
// A match in a comment belongs to the comment's owner; utils and
// constraints are accepted.
let comment = rust(
json!({
"rule": {"matches": "doc"},
"utils": {"doc": {"kind": "line_comment", "regex": "unwrap"}}
}),
"src/lib.rs",
)
.unwrap();
assert_eq!(found(&comment), ["src/lib.rs#fn[second]"]);
let constrained = rust(
json!({
"rule": {"pattern": "$X.unwrap()"},
"constraints": {"X": {"regex": "^[ab]$"}}
}),
"src",
)
.unwrap();
assert_eq!(found(&constrained), ["src/lib.rs#mod[inner]/fn[third]"]);
let python = dispatch(
&sources,
"ast_grep",
&json!({"language":"python","rule":{"rule":{"pattern":"$X.unwrap()"}}}),
)
.unwrap();
assert_eq!(found(&python), ["src/tool.py#"]);
let none = rust(json!({"rule":{"pattern":"missing()"}}), ".").unwrap();
assert_eq!(none.result["matches"], json!([]));
assert!(none.inputs.is_empty());
for (arguments, message) in [
(
json!({"language":"cobol","rule":{"rule":{"kind":"x"}}}),
"unknown structural search language",
),
(
json!({"rule":{"rule":{"kind":"x"}}}),
"language must be a string",
),
(
json!({"language":"rust","rule":"x"}),
"rule must be an object",
),
(
json!({"language":"rust","rule":{"rule":{"kind":"no_such_kind"}}}),
"invalid ast-grep rule",
),
(
json!({"language":"rust","rule":{"pattern":"x"}}),
"unexpected key \"pattern\"",
),
(
json!({"language":"rust","rule":{"rule":{"kind":"x"}},"extra":1}),
"unexpected tool argument \"extra\"",
),
(
json!({"query":"x","language":"rust"}),
"unexpected tool argument \"language\"",
),
(
json!({"query":"x"}),
"must have the form <full-name>/<query-name>",
),
(
json!({"query":"requirements.none/sites"}),
"names no declared requirement",
),
(
json!({"query":"requirements.ready/sites"}),
"declares no query named \"sites\"",
),
] {
let error = dispatch(&sources, "ast_grep", &arguments).err().unwrap();
assert!(error.to_string().contains(message), "{arguments}: {error}");
}
// A matched file that cannot be parsed fails the search.
fs::write(
root.path().join("src/broken.rs"),
"fn broken() {\n q.unwrap();\n}\n}\n",
)
.unwrap();
let error = rust(json!({"rule":{"pattern":"$X.unwrap()"}}), "src")
.err()
.unwrap();
assert!(error.to_string().contains("syntax error"), "{error}");
assert!(sources.recorded_inputs().is_empty());
}
Input 34: outline tests/authoring_batch.rs fn[a_denied_read_returns_an_error_and_its_assessment_continues]
- File:
tests/authoring_batch.rs - Selector:
fn[a_denied_read_returns_an_error_and_its_assessment_continues] - Kind:
fn tests/authoring_batch.rs:1151–1208
// {test}`requirements.authoring.batch`
// {test}`requirements.authoring.read_denial`
// {test}`requirements.authoring.usage_storage`
#[test]
fn a_denied_read_returns_an_error_and_its_assessment_continues() {
let server = Server::start_with(
false,
Behavior::DeniedRead {
subject: "example requirements.alpha_case",
hold_other_requests: false,
},
);
let fixture = Fixture::new(&server.endpoint, Some(1));
fs::create_dir(fixture.project.join("evidence")).unwrap();
fs::write(
fixture.project.join("evidence/private.txt"),
"generated output\n",
)
.unwrap();
let output = fixture.run(&["author", "--all"]);
assert!(output.status.success(), "{output:?}");
let subjects = server.subjects();
// The denied assessment made a second request after the tool error.
assert_eq!(
subjects
.iter()
.filter(|subject| *subject == "example requirements.alpha_case")
.count(),
2,
"{subjects:?}"
);
for name in [
"requirements.alpha",
"requirements.alpha_case",
"requirements.beta",
"requirements.gamma",
] {
assert_eq!(fixture.evidence(name)["determination"], true, "{name}");
}
let usage = fixture.usage();
assert!(
usage.iter().all(|run| run["outcome"] == "completed"),
"{usage:?}"
);
let denied = usage
.iter()
.find(|run| run["subject"] == "requirements.alpha_case")
.unwrap();
assert_eq!(denied["request_count"], 2);
assert_eq!(denied["tool_failures"]["habeas"], 1);
// The denied file is not recorded.
assert!(
!fixture
.evidence("requirements.alpha_case")
.to_string()
.contains("private.txt")
);
}
Input 35: outline tests/authoring_cli.rs fn[explicit_untracked_reads_return_an_untracked_error_and_the_assessment_continues]
- File:
tests/authoring_cli.rs - Selector:
fn[explicit_untracked_reads_return_an_untracked_error_and_the_assessment_continues] - Kind:
fn tests/authoring_cli.rs:853–922
// {test}`requirements.authoring.read_denial`
// {test}`requirements.authoring.file_discovery`
// {test}`requirements.authoring.text_search`
// {test}`requirements.authoring.structural_search`
// {test}`requirements.authoring.source_tools`
// {test}`requirements.authoring.persistence`
// {test}`requirements.authoring.usage_storage`
// {test}`requirements.authoring.usage_requests`
// {test}`requirements.authoring.read_denial.untracked`
// {test}`requirements.authoring.read_denial`
#[test]
fn explicit_untracked_reads_return_an_untracked_error_and_the_assessment_continues() {
for (tool, arguments) in [
("habeas", json!({"file":"untracked.txt", "line_start":1})),
(
"ripgrep",
json!({"path":"untracked.txt", "pattern":"hidden"}),
),
(
"ast_grep",
json!({"path":"untracked.txt", "language":"rust", "rule":{"rule":{"pattern":"hidden"}}}),
),
("list_files", json!({"path":"untracked-directory"})),
] {
let server = Server::start(vec![
reply(vec![call("denied", tool, arguments)]),
reply(vec![call(
"submit",
"submit_judgment",
json!({"determination": true, "rationale": "The tracked sources support it."}),
)]),
]);
let fixture = Fixture::new(&server.endpoint);
for args in [["init", "--quiet"], ["add", "."]] {
let git = Command::new("git")
.current_dir(&fixture.project)
.args(args)
.output()
.unwrap();
assert!(git.status.success(), "{git:?}");
}
fs::write(fixture.project.join("untracked.txt"), "hidden source\n").unwrap();
fs::create_dir(fixture.project.join("untracked-directory")).unwrap();
fs::write(
fixture.project.join("untracked-directory/hidden.txt"),
"hidden source\n",
)
.unwrap();
let output = fixture.run(&["author", SUBJECT, "--stdout"]);
assert!(output.status.success(), "{tool}: {output:?}");
// The model was told the path is untracked and how to fix it, and
// the file was neither delivered nor recorded.
let requests = server.finish();
assert_eq!(requests.len(), 2, "{tool}");
let second = requests[1].body.to_string();
assert!(
second.contains("is untracked") || second.contains("untracked, so"),
"{tool}: {second}"
);
assert!(second.contains("git add"), "{tool}: {second}");
assert!(!second.contains("hidden source"), "{tool}: {second}");
let evidence = String::from_utf8_lossy(&output.stdout);
assert!(!evidence.contains("untracked"), "{tool}: {evidence}");
let usage = fixture.usage();
assert_eq!(usage["outcome"], "completed", "{tool}: {usage}");
assert_eq!(usage["request_count"], 2, "{tool}: {usage}");
assert_eq!(usage["tool_failures"][tool], 1, "{tool}: {usage}");
}
}
Referenced definitions
Input 2: requirements selection requirements.authoring.not_listed
requirements.authoring.not_listed:md/requirements/authoring.md:605–618
:::{req} not_listed
A `list_files`, `ripgrep`, or `ast_grep` result MUST include `not_listed`, an
array of `{path, reason}` with reason `untracked`, naming each untracked file
inside the project that the listing would otherwise include or that contains a
match, so the model can tell that sources exist which it cannot read. It MUST
be omitted when there are none, and for a paged result it MUST appear on the
first page, continuing across subsequent pages when needed to obey the page
size limit. Page counts MUST include these entries as well as the ordinary
result entries, and each array MUST retain its order. It MUST NOT give those
files' contents, and they MUST NOT become
evidence inputs. Files excluded for another reason, such as a workspace disallow
rule or generated `evidence/` output, MUST NOT be read to find matches and MUST
NOT be listed.
:::
Other sources
Input 1: requirements selection requirements.authoring.read_denial
requirements.authoring.read_denial:md/requirements/authoring.md:701–708
:::{req} read_denial
When source-access policy denies a path that a model tool call names
explicitly, the harness MUST return a tool error naming the path and the reason
it cannot be read, add no evidence input, and continue the assessment.
Discovery and search MUST leave denied candidates out of their entries,
reporting untracked ones under {cite}`requirements.authoring.not_listed`. Malformed tool
arguments and ordinary read failures MUST also return explanatory tool errors.
:::