interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-runtime / tests / requirements_test.rs

621 lines · 24352 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Requirement validation for composed documents (crate::requirements).
17//! The retry loop is driven through `ComposeBridge::run_task`
18//! (tests/support/compose_harness.rs).
19#[path = "support/compose_harness.rs"]
20mod compose_harness;
21#[path = "support/home_guard.rs"]
22mod home_guard;
23
24use aien_runtime::approved::{approved_proposal_sha256, proposal_text};
25use aien_runtime::control::ControlResponse;
26use aien_runtime::effects;
27use aien_runtime::requirements::{extract, refusal_reason, unmet, ItemKind, Requirement};
28use aien_runtime::{check_file_proposal, ComposeBridge, ComposeProposer, Generation};
29use compose_harness::{always, replies, Asked, Harness};
30use std::sync::{Arc, Mutex};
31use std::time::Duration;
32
33fn doc(n: usize) -> String {
34 let mut s = String::from("filename: DOC.md\n");
35 for i in 0..n {
36 s.push_str(&format!("line {i}\n"));
37 }
38 s
39}
40
41fn gen(text: String) -> Result<Generation, String> {
42 Ok(Generation {
43 text,
44 tokens: 5,
45 finish_reason: Some("eos".into()),
46 ..Default::default()
47 })
48}
49
50#[test]
51fn extracts_each_supported_pattern() {
52 use ItemKind::*;
53 use Requirement::*;
54 assert_eq!(
55 extract("Write a note in at least 20 lines."),
56 [MinLines(20)]
57 );
58 assert_eq!(extract("keep it to AT MOST 8 lines"), [MaxLines(8)]);
59 assert_eq!(extract("give at least 5 items"), [MinItems(Items, 5)]);
60 assert_eq!(extract("give at least 1 item"), [MinItems(Items, 1)]);
61 assert_eq!(
62 extract("list at least 3 steps, please"),
63 [MinItems(Steps, 3)]
64 );
65 assert_eq!(extract("with at least 4 sections"), [MinItems(Sections, 4)]);
66 assert_eq!(
67 extract("ask at least 6 questions."),
68 [MinItems(Questions, 6)]
69 );
70 assert_eq!(
71 extract("include the phrase \"Hello World\" and contain the phrase \"x\""),
72 [RequiredPhrases(vec!["Hello World".into(), "x".into()])]
73 );
74 assert_eq!(
75 extract("at least 20 lines and at most 40 lines"),
76 [MinLines(20), MaxLines(40)]
77 );
78}
79
80#[test]
81fn unsupported_phrasing_is_not_extracted() {
82 for g in [
83 "write a long document",
84 "at least 20 long lines",
85 "at most 20 paragraphs",
86 "at most 5 items",
87 "at least 0 lines",
88 "at least -3 lines",
89 "at least 2.5 lines",
90 "at least 99999999999999999999999 lines",
91 "include the phrase hello",
92 "include the phrase \"\"",
93 "mention hello in the text",
94 "exactly 20 lines",
95 ] {
96 assert_eq!(extract(g), vec![], "{g}");
97 }
98}
99
100#[test]
101fn checks_pass_and_fail_with_exact_counts() {
102 use ItemKind::*;
103 use Requirement::*;
104 let thirteen: String = (0..13).map(|i| format!("l{i}\n\n")).collect();
105 assert_eq!(non_empty_blank_safe(&thirteen), 13);
106 assert!(MinLines(13).check(&thirteen).is_none());
107 assert_eq!(
108 MinLines(20).check(&thirteen).unwrap(),
109 "at least 20 non-empty lines, found 13"
110 );
111 assert!(MaxLines(13).check(&thirteen).is_none());
112 assert!(MaxLines(12).check(&thirteen).is_some());
113 let md = "# One\n## Two\n#NoSpace\n####### seven\n- a\n * b\n+ c\n1. d\n2) e\n3.f\nWhy?\nreally ?\n";
114 assert!(MinItems(Sections, 2).check(md).is_none());
115 assert!(MinItems(Sections, 3).check(md).is_some());
116 assert!(MinItems(Items, 5).check(md).is_none());
117 assert!(MinItems(Items, 6).check(md).is_some());
118 assert!(MinItems(Steps, 2).check(md).is_none());
119 assert!(MinItems(Steps, 3).check(md).is_some());
120 assert!(MinItems(Questions, 2).check(md).is_none());
121 assert!(MinItems(Questions, 3).check(md).is_some());
122 let p = RequiredPhrases(vec!["hello world".into(), "Bye".into()]);
123 assert_eq!(
124 p.check("HeLLo WoRLD only").unwrap(),
125 "the phrase \"hello world\", \"Bye\", missing \"Bye\""
126 );
127 assert!(p.check("Hello World and BYE").is_none());
128 assert_eq!(unmet(&[], "x"), Vec::<String>::new());
129 assert_eq!(refusal_reason(&[], "x"), None);
130}
131
132fn non_empty_blank_safe(s: &str) -> usize {
133 s.lines().filter(|l| !l.trim().is_empty()).count()
134}
135
136/// The goal of the document tests below: a new DOC.md, at least 20 lines.
137const DOC_GOAL: &str = "write DOC.md in at least 20 lines";
138
139#[test]
140#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")]
141fn retry_names_the_unmet_requirement_and_second_attempt_passes() {
142 let _home = home_guard::home_slot();
143 let h = Harness::new(replies(&[&doc(13), &doc(25)]));
144 let r = h.run(DOC_GOAL).unwrap();
145 assert_eq!(r.proposal.as_deref(), Some(doc(25).as_str()), "{r:?}");
146 let a = &r.proposal_attempts;
147 assert_eq!(a.len(), 2);
148 assert_eq!(a[0].outcome, "refused");
149 assert_eq!(
150 a[0].reason.as_deref(),
151 Some("unmet requirement: at least 20 non-empty lines, found 13")
152 );
153 assert_eq!(
154 a[0].unmet_requirements,
155 ["at least 20 non-empty lines, found 13"]
156 );
157 assert_eq!(a[1].outcome, "parsed");
158 assert!(a[1].unmet_requirements.is_empty());
159 let p: Vec<String> = h.calls().into_iter().map(|c| c.prompt).collect();
160 assert!(!p[0].contains("unmet requirement"));
161 assert!(
162 p[1].contains("refused before anything was written (unmet requirement: at least 20 non-empty lines, found 13)"),
163 "{}",
164 p[1]
165 );
166 // sc#384 v8: the refused reply itself is quoted back for correction.
167 assert!(
168 p[1].contains(&format!("<<<REFUSED ANSWER\n{}", doc(13))),
169 "{}",
170 p[1]
171 );
172}
173
174#[test]
175#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")]
176fn exhaustion_returns_no_proposal() {
177 let _home = home_guard::home_slot();
178 let h = Harness::new(always(&doc(13)));
179 let r = h.run(DOC_GOAL).unwrap();
180 assert!(
181 r.proposal.is_none() && r.uncommitted_proposal.is_none(),
182 "{r:?}"
183 );
184 let why = r.proposer_error.unwrap();
185 assert!(
186 why.contains("at least 20 non-empty lines, found 13"),
187 "{why}"
188 );
189 let a = &r.proposal_attempts;
190 assert_eq!(a.len(), 3);
191 assert!(a
192 .iter()
193 .all(|x| x.outcome == "refused" && x.aegis.is_none()));
194 assert!(a.iter().all(|x| x.unmet_requirements.len() == 1));
195}
196
197// deadline_is_shared_across_attempts needs a short document budget: it is in
198// compose_budget_test.rs (same name).
199
200#[test]
201#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")]
202fn validated_document_is_the_one_approval_binds() {
203 let _home = home_guard::home_slot();
204 let goal = "write DOC.md with at least 4 lines";
205 let reqs = extract("at least 4 lines");
206 assert_eq!(extract(goal), reqs);
207 let h = Harness::new(always("filename: DOC.md\na\nb\nc\nd\n"));
208 let r = h.run(goal).unwrap();
209 let text = r.proposal.unwrap();
210 let saved = check_file_proposal(&text).unwrap();
211 // The content that passed is the content that would be written ...
212 assert!(refusal_reason(&reqs, &saved.content).is_none());
213 // ... and it reads back byte for byte through the approval template, so
214 // the digest an approval binds is the digest of the saved bytes.
215 assert_eq!(proposal_text(&saved.path, &saved.content).unwrap(), text);
216 let bound = approved_proposal_sha256(&saved.path, &saved.content);
217 let again = check_file_proposal(&proposal_text(&saved.path, &saved.content).unwrap()).unwrap();
218 assert_eq!(approved_proposal_sha256(&again.path, &again.content), bound);
219}
220
221#[test]
222#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")]
223fn edit_mode_validates_the_merged_file_not_the_reply() {
224 let _home = home_guard::home_slot();
225 // The prior file has 3 lines; the reply adds 2: the saved file has 5.
226 let h = Harness::new(always("filename: N.md\n# T\na\nnew1\nnew2\nb\n"));
227 h.write("N.md", "# T\na\nb\n");
228 let goal = |n: usize| format!("Edit N.md so that it has at least {n} lines.");
229 assert_eq!(extract(&goal(5)), [Requirement::MinLines(5)]);
230 assert_eq!(extract(&goal(6)), [Requirement::MinLines(6)]);
231 let r = h.run(&goal(5)).unwrap();
232 assert_eq!(
233 check_file_proposal(&r.proposal.unwrap()).unwrap().content,
234 "# T\na\nnew1\nnew2\nb\n"
235 );
236 let r = h.run(&goal(6)).unwrap();
237 assert!(r.proposal.is_none() && r.proposer_error.is_some(), "{r:?}");
238 assert_eq!(
239 r.proposal_attempts[0].unmet_requirements,
240 ["at least 6 non-empty lines, found 5"]
241 );
242 assert!(h.calls().iter().all(|c| c.asked == Asked::Edit));
243}
244
245#[test]
246fn unmet_requirement_leaves_nothing_committed_or_written() {
247 let _home = home_guard::home_slot();
248 let tmp = tempfile::tempdir().unwrap();
249 let ws = tmp.path().join("ws");
250 std::fs::create_dir_all(&ws).unwrap();
251 let proposer: ComposeProposer = Arc::new(|_: &str, _: Duration| gen(doc(13)));
252 let bridge = ComposeBridge::new(tmp.path().join("compose"), proposer, "test:short")
253 .with_authorize_requires_desk(false);
254 let resp = bridge.run_task("write DOC.md in at least 20 lines", ws.to_str().unwrap());
255 if !aien_omega_compose::LINKED {
256 assert!(matches!(resp, ControlResponse::Error(_)));
257 return;
258 }
259 let ControlResponse::ComposeTaskResult(r) = resp else {
260 panic!("{resp:?}")
261 };
262 assert!(!r.committed, "{r:?}");
263 assert!(r.proposal.is_none());
264 assert_eq!(r.requirements_recognized, ["at least 20 non-empty lines"]);
265 assert_eq!(r.proposal_attempts.len(), 3);
266 assert!(r.proposer_error.unwrap().contains("found 13"));
267 assert_eq!(std::fs::read_dir(&ws).unwrap().count(), 0);
268}
269
270// ---- linked proofs (real omega compose library; skipped in the CPU stub) ----
271
272fn sha256_hex(b: &[u8]) -> String {
273 aien_omega_compose::hex(&<sha2::Sha256 as sha2::Digest>::digest(b))
274}
275
276fn recalled(b: &ComposeBridge) -> aien_runtime::control::ComposeRecallReport {
277 match b.recall(&[], None) {
278 ControlResponse::ComposeRecalled(r) => *r,
279 other => panic!("recall: {other:?}"),
280 }
281}
282
283fn dir_names(d: &std::path::Path) -> Vec<String> {
284 let mut v: Vec<String> = std::fs::read_dir(d)
285 .unwrap()
286 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
287 .collect();
288 v.sort();
289 v
290}
291
292/// Every attempt of a real compose run fails the requirement: nothing is
293/// proposed, approved, written, committed or recorded as an effect.
294#[test]
295fn linked_exhaustion_leaves_ledger_state_and_files_untouched() {
296 let _home = home_guard::home_slot();
297 let tmp = tempfile::tempdir().unwrap();
298 let ws = tmp.path().join("ws");
299 std::fs::create_dir_all(&ws).unwrap();
300 let home = tmp.path().join("compose");
301 let calls = Arc::new(Mutex::new(0usize));
302 let c2 = calls.clone();
303 let proposer: ComposeProposer = Arc::new(move |_: &str, _: Duration| {
304 *c2.lock().unwrap() += 1;
305 gen(doc(13))
306 });
307 let bridge = ComposeBridge::new(home.clone(), proposer, "test:short")
308 .with_authorize_requires_desk(false);
309 let resp = bridge.run_task("write DOC.md in at least 20 lines", ws.to_str().unwrap());
310 if !aien_omega_compose::LINKED {
311 assert!(matches!(resp, ControlResponse::Error(_)));
312 return;
313 }
314 let ControlResponse::ComposeTaskResult(r) = resp else {
315 panic!("{resp:?}")
316 };
317 // The real model Skill ran 3 times (the attempt cap), each refused.
318 assert_eq!(*calls.lock().unwrap(), 3);
319 assert!(r
320 .proposal_attempts
321 .iter()
322 .all(|a| a.outcome == "refused" && a.aegis.is_none()));
323 // No committed proposal, no winner, no AEGIS pass, no promotion record.
324 assert!(!r.committed, "{r:?}");
325 assert_eq!(r.outcome, 2, "RXC_OUT_NO_WINNER: {r:?}");
326 assert!(r.proposal.is_none() && r.proposal_sha256.is_none());
327 assert!(r.proposal_path.is_none() && r.proposal_content_sha256.is_none());
328 assert_eq!((r.winner, r.aegis_pass_mask), (None, 0), "{r:?}");
329 assert_eq!(r.cx_promotion, 0, "{r:?}");
330 // No approval request, no effect intent: the host ledger holds no
331 // authorization or effect note, and rebuilds to an empty ledger.
332 let rec = recalled(&bridge);
333 assert!(
334 rec.host
335 .iter()
336 .all(|h| !matches!(h.note.as_deref(), Some("authorization") | Some("effect"))),
337 "{:?}",
338 rec.host
339 );
340 let ledger = effects::Ledger::from_records(&rec.host).unwrap();
341 assert!(ledger.grants.is_empty() && ledger.intents.is_empty());
342 assert!(ledger.approved_by_claim.is_empty() && ledger.spent.is_empty());
343 // No file was written and the destination is absent.
344 assert!(!ws.join("DOC.md").exists());
345 assert_eq!(dir_names(&ws), Vec::<String>::new());
346 // The compose home holds only composition files.
347 for n in dir_names(&home) {
348 assert!(
349 n == "machine.id" || n == "cortex.cx" || n.starts_with("jspace"),
350 "{n}"
351 );
352 }
353 // Compose state is unchanged by the failed task: a second identical task
354 // adds no promotion and the committed World has no new document.
355 let before = recalled(&bridge).records_total;
356 let again = bridge.run_task("write DOC.md in at least 20 lines", ws.to_str().unwrap());
357 let ControlResponse::ComposeTaskResult(r2) = again else {
358 panic!("{again:?}")
359 };
360 assert!(!r2.committed && r2.cx_promotion == 0, "{r2:?}");
361 assert!(!ws.join("DOC.md").exists());
362 let after = recalled(&bridge);
363 assert!(after.records_total >= before);
364 assert!(after
365 .host
366 .iter()
367 .all(|h| !matches!(h.note.as_deref(), Some("authorization") | Some("effect"))));
368}
369
370/// A document that passes validation commits through the real compose run,
371/// is approved by an authorization bound to its digest, and is saved with
372/// sha256(disk) == the approved content sha256.
373#[test]
374fn linked_passing_document_is_approved_and_saved_byte_for_byte() {
375 let _home = home_guard::home_slot();
376 let tmp = tempfile::tempdir().unwrap();
377 let ws = tmp.path().join("ws");
378 std::fs::create_dir_all(&ws).unwrap();
379 let ws = std::fs::canonicalize(&ws).unwrap();
380 let proposer: ComposeProposer = Arc::new(|_: &str, _: Duration| gen(doc(25)));
381 let bridge = ComposeBridge::new(tmp.path().join("compose"), proposer, "test:long")
382 .with_authorize_requires_desk(false);
383 let resp = bridge.run_task("write DOC.md in at least 20 lines", ws.to_str().unwrap());
384 if !aien_omega_compose::LINKED {
385 assert!(matches!(resp, ControlResponse::Error(_)));
386 return;
387 }
388 let ControlResponse::ComposeTaskResult(r) = resp else {
389 panic!("{resp:?}")
390 };
391 assert!(r.committed, "{r:?}");
392 assert_eq!(r.proposal_attempts.len(), 1);
393 assert_eq!(r.proposal_attempts[0].aegis.as_deref(), Some("pass"));
394 let proposal = r.proposal.clone().unwrap();
395 let saved = check_file_proposal(&proposal).unwrap();
396 assert!(refusal_reason(&extract("at least 20 lines"), &saved.content).is_none());
397 let content_sha = r.proposal_content_sha256.clone().unwrap();
398 assert_eq!(content_sha, sha256_hex(saved.content.as_bytes()));
399 assert!(!ws.join("DOC.md").exists(), "composing writes nothing");
400 // Approval (the authorization note) binds the digest; the effect writes.
401 let target = ws.join(&saved.path);
402 // sovereign-core #261: the daemon mints the grant from its own commit record.
403 let a = match effects::mint_grant(
404 &bridge,
405 &effects::MintRequest {
406 cx_promotion: r.cx_promotion,
407 proposal_sha256: r.proposal_sha256.clone().unwrap(),
408 workspace: ws.display().to_string(),
409 approver: "drake".into(),
410 constraints: vec![],
411 },
412 ) {
413 ControlResponse::ComposeNoted(n) => n.id,
414 other => panic!("authorize: {other:?}"),
415 };
416 let (pid, start) = effects::self_executor();
417 let i = match effects::open_intent(
418 &bridge,
419 &effects::IntentRequest {
420 authorization: a,
421 proposal_sha256: r.proposal_sha256.clone().unwrap(),
422 path: saved.path.clone(),
423 target: target.display().to_string(),
424 content_sha256: content_sha.clone(),
425 executor_pid: pid,
426 executor_start: start,
427 },
428 ) {
429 ControlResponse::ComposeNoted(n) => n.id,
430 other => panic!("intent: {other:?}"),
431 };
432 std::fs::write(&target, &saved.content).unwrap();
433 assert!(matches!(
434 effects::ack(
435 &bridge,
436 i,
437 &serde_json::json!({"written_sha256": content_sha})
438 ),
439 ControlResponse::ComposeNoted(_)
440 ));
441 assert_eq!(sha256_hex(&std::fs::read(&target).unwrap()), content_sha);
442 let ledger = effects::Ledger::from_records(&recalled(&bridge).host).unwrap();
443 assert_eq!(ledger.intents.len(), 1);
444}
445
446// ---- review fixes (#287) ----
447
448#[test]
449fn count_followed_by_a_qualifier_is_not_extracted() {
450 // The noun must END the clause: "N lines of context" states something
451 // other than "the document has N lines", so it gets no check.
452 for g in [
453 "show a diff with at least 3 lines of context",
454 "write at least 2 sections of the config",
455 "at least 5 items per category",
456 "at least 3 steps for each stage",
457 "at least 4 questions in the survey",
458 "at least 4 questions from the list",
459 "at least 6 lines for the intro",
460 "at most 10 lines in each file",
461 ] {
462 assert_eq!(extract(g), vec![], "{g}");
463 }
464 use Requirement::*;
465 // Clause-ending punctuation, end of goal, and the joining words are fine.
466 for (g, want) in [
467 ("at least 20 lines", MinLines(20)),
468 ("at least 20 lines.", MinLines(20)),
469 ("at least 20 lines, please", MinLines(20)),
470 ("at least 20 lines and a title", MinLines(20)),
471 ("at least 20 lines or more", MinLines(20)),
472 ("at least 20 lines that explain it", MinLines(20)),
473 ("at most 8 lines which are short", MaxLines(8)),
474 ("at least 6 lines with comments", MinLines(6)),
475 ("at least 6 lines about cats", MinLines(6)),
476 ("at least 20 lines long", MinLines(20)),
477 ] {
478 assert_eq!(extract(g), [want], "{g}");
479 }
480}
481
482#[test]
483fn covering_after_a_count_adds_a_topic_requirement() {
484 assert_eq!(
485 extract("at least 20 lines covering the topic"),
486 [
487 Requirement::MinLines(20),
488 Requirement::RequiredTopics(vec!["the topic".into()])
489 ]
490 );
491}
492
493#[test]
494fn phrase_followed_by_a_qualifier_is_not_extracted() {
495 // "in the title" would make the whole-document check claim more than it covers.
496 assert_eq!(extract("include the phrase \"X\" in the title"), vec![]);
497 assert_eq!(
498 extract("include the phrase \"X\" in the title and contain the phrase \"Y\"."),
499 [Requirement::RequiredPhrases(vec!["Y".into()])]
500 );
501}
502
503#[test]
504fn negated_wording_is_not_extracted() {
505 for g in [
506 "do not include the phrase \"X\"",
507 "Do NOT include the phrase \"X\"",
508 "never contain the phrase \"X\"",
509 "the file must not include the phrase \"X\"",
510 "don't include the phrase \"X\"",
511 "it doesn't contain the phrase \"X\"",
512 "without ever including; never include the phrase \"X\"",
513 "not at least 20 lines",
514 "do not write at least 20 lines",
515 "never write at least 3 sections",
516 "it must not have at most 5 lines",
517 "not at most 10 lines",
518 "without at least 4 items",
519 ] {
520 assert_eq!(extract(g), vec![], "{g}");
521 }
522 // A negation in an EARLIER clause does not poison a later requirement.
523 assert_eq!(
524 extract("do not use tables. Write at least 20 lines."),
525 [Requirement::MinLines(20)]
526 );
527 assert_eq!(
528 extract("do not hedge, include the phrase \"X\""),
529 [Requirement::RequiredPhrases(vec!["X".into()])]
530 );
531}
532
533#[test]
534fn emphasis_and_quoted_forms_are_unrecognized() {
535 // Documented limitation: markdown emphasis or quotes around the wording
536 // break the exact word sequence, so nothing is extracted (and nothing is
537 // claimed as covered).
538 for g in [
539 "write **at least 20 lines**",
540 "write \"at least 20 lines\"",
541 "write 'at least 20 lines'",
542 "write at least **20** lines",
543 "write at least 20 *lines*",
544 "write at least 20 `lines`",
545 ] {
546 assert_eq!(extract(g), vec![], "{g}");
547 }
548}
549
550#[test]
551fn fenced_code_is_not_counted_as_headings_questions_items_or_steps() {
552 use ItemKind::*;
553 let d = "# Real\n- a\n1. s\nWhy?\n```bash\n# not a heading\n- not an item\n1. not a step\nnot a question?\n```\n~~~\n## also not\n- nor this\nq?\n~~~\n";
554 assert_eq!(count(Sections, d), 1);
555 assert_eq!(count(Items, d), 2);
556 assert_eq!(count(Steps, d), 1);
557 assert_eq!(count(Questions, d), 1);
558 // CommonMark close rule: a shorter or info-carrying fence does not close.
559 let d2 = "````\n```\n# inside\n```bash\n- inside\n````\n# outside\n";
560 assert_eq!(count(Sections, d2), 1);
561 // ~~~ is not closed by ``` and vice versa.
562 let d3 = "~~~\n```\n# inside\n~~~\n# outside\n";
563 assert_eq!(count(Sections, d3), 1);
564 // An unclosed fence runs to the end of the document.
565 assert_eq!(count(Sections, "# a\n```\n# b\n# c\n"), 1);
566 // A backtick fence whose info string holds a backtick is not a fence.
567 assert_eq!(count(Sections, "``` `x`\n# real\n"), 1);
568}
569
570fn count(k: ItemKind, s: &str) -> usize {
571 // found N appears in the unmet sentence; ask for an impossible minimum.
572 let m = Requirement::MinItems(k, usize::MAX).check(s).unwrap();
573 m.rsplit("found ").next().unwrap().parse().unwrap()
574}
575
576#[test]
577fn line_limits_count_every_non_empty_line_including_code_and_fences() {
578 // Documented: MinLines/MaxLines count lines of the file, so fence marker
579 // lines and code lines count; blank lines do not.
580 let d = "intro\n```rust\nlet x = 1;\n\nlet y = 2;\n```\nend\n";
581 assert_eq!(Requirement::MinLines(6).check(d), None);
582 assert_eq!(
583 Requirement::MinLines(7).check(d).unwrap(),
584 "at least 7 non-empty lines, found 6"
585 );
586 assert_eq!(Requirement::MaxLines(6).check(d), None);
587 assert!(Requirement::MaxLines(5).check(d).is_some());
588}
589
590#[test]
591#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")]
592fn edit_whose_prior_file_already_breaks_a_max_is_refused_before_any_attempt() {
593 let _home = home_guard::home_slot();
594 let prior: String = (0..10).map(|i| format!("l{i}\n")).collect();
595 let h = Harness::new(always("filename: N.md\nl0\nnew\n"));
596 h.write("N.md", &prior);
597 let goal = |n: usize| format!("Add a line to N.md and keep it to at most {n} lines.");
598 assert_eq!(extract(&goal(5)), [Requirement::MaxLines(5)]);
599 assert_eq!(extract(&goal(12)), [Requirement::MaxLines(12)]);
600 let r = h.run(&goal(5)).unwrap();
601 assert_eq!(h.calls().len(), 0, "no attempt may be spent");
602 assert!(r.proposal.is_none() && !r.committed, "{r:?}");
603 let why = r.proposer_error.unwrap();
604 assert!(
605 why.contains("N.md") && why.contains("at most 5 non-empty lines, found 10"),
606 "{why}"
607 );
608 assert!(why.contains("an edit only adds lines"), "{why}");
609 let a = &r.proposal_attempts;
610 assert_eq!(a.len(), 1);
611 assert_eq!(a[0].outcome, "refused");
612 assert_eq!(a[0].reason.as_deref(), Some(why.as_str()));
613 assert_eq!(
614 a[0].unmet_requirements,
615 ["at most 5 non-empty lines, found 10"]
616 );
617 // Min requirements and a prior file within the maximum are unaffected.
618 let r = h.run(&goal(12)).unwrap();
619 assert!(r.proposal.is_some(), "{r:?}");
620 assert_eq!(h.calls().len(), 1);
621}