"""صفحة المرجع، وقائمة المراجع — تقرير معايير التوثيق. قِيست على تشغيلات حقيقية قبل العلاج: ٨٢ استشهادًا من ٨٣ على ست حقائب يبدأ من الصفحة ١، لأن كل مصدر كان يُقرأ من أول حرف فيه، فالصفحة المذكورة صفحةُ غلاف المستند لا صفحةُ الفكرة. حقيبة من يومين خرجت بـ ١٢٥ مرجعًا، ١٢٠ منها لم يُستشهد به في المتن، و٧١٪ منها مكتوب فيه «(د.ت)»، وفيها «مشروع الكاجو في مصر» و«بكالوريوس الجيولوجيا العامة» في حقيبة عن التطوير العقاري — لأن القائمة كانت تُبنى من كل رابط نزّله البحث لا من المصادر التي استعملها النص. """ from __future__ import annotations import json import pytest from app.agents.arabic_bag.citations import citation_block, in_text, pages_for from app.agents.arabic_bag.references import ( _work_key, cited_urls, drop_stale, is_in_text_marker, orphan_citations, ) from app.agents.arabic_bag.search import _best_window # ═══════════════════════════════════════════ صفحة الفكرة لا صفحة الغلاف def _pages(*spec): return [(number, text) for number, text in spec] def test_the_window_is_the_pages_that_discuss_the_cover(): pages = _pages( (1, "صفحة الغلاف واسم الجامعة والمشرف. " * 10), (2, "فهرس المحتويات وقائمة الجداول. " * 10), (18, "المخاطرة المحسوبة في التطوير العقاري. " * 10), (19, "أدوات إدارة المخاطرة المحسوبة عمليًا. " * 10), ) excerpt, first, last = _best_window(pages, "المخاطرة المحسوبة التطوير العقاري") assert (first, last) == (18, 19) assert "فهرس المحتويات" not in excerpt def test_a_narrower_window_wins_over_a_wider_one_of_the_same_score(): """نافذة تحمل الدرجة نفسها في صفحتين أدقّ في الإحالة من نافذة تبلغها في خمس، وابتلاع صفحات لا تخصّ الموضوع يعيد المشكلة نفسها.""" pages = _pages( (1, "مقدمة عامة لا تخص الموضوع. " * 8), (2, "تمهيد عام آخر. " * 8), (3, "التسويق العقاري وقنوات الترويج الرقمية. " * 8), ) _, first, last = _best_window(pages, "التسويق العقاري قنوات الترويج") assert (first, last) == (3, 3) def test_a_document_that_never_mentions_the_cover_yields_its_opening(): """وهو ما كان يُعاد قبل هذا، وهو الصدق في وصف المقتطف.""" pages = _pages((4, "نص لا علاقة له. " * 8), (5, "ولا هذا. " * 8)) excerpt, first, last = _best_window(pages, "الذكاء الاصطناعي التوليدي") assert first == 4 and excerpt assert last in (4, 5) def test_the_document_s_own_page_number_is_used(): """صفحةٌ رقمها ١٧ لا تُسمّى الأولى لأن ما قبلها لم يُستخرج.""" pages = _pages((17, "الأمن الفكري لدى الطلاب الجامعيين. " * 10)) _, first, last = _best_window(pages, "الأمن الفكري الطلاب") assert (first, last) == (17, 17) def test_the_citation_reads_the_recorded_range_not_the_arithmetic(): source = {"pages": [19, 21], "page_lengths": [1200, 1200, 1200, 1200]} assert pages_for(source, 2500) == (19, 21) def test_a_source_read_before_the_window_existed_still_works(): """تشغيلة قديمة لا تحمل `pages`، فيُحسب المدى من أطوال الصفحات كما كان.""" assert pages_for({"page_lengths": [1200, 1100, 900]}, 2500) == (1, 3) assert pages_for({"page_lengths": []}, 2500) is None def test_the_page_marker_carries_its_dot(): assert in_text("العتيبي", "2023", (19, 19)) == "(العتيبي، 2023، ص. 19)" assert in_text("العتيبي", "2023", (19, 21)) == "(العتيبي، 2023، ص ص. 19-21)" assert in_text("Smith", "2023", (19, 21)) == "(Smith, 2023, pp. 19-21)" def test_two_covers_of_one_document_can_cite_two_different_pages(): """«يمنع تكرار رقم الصفحة نفسه في عدة مواضع مختلفة دون تحقق».""" pages = _pages( (5, "التمويل الذاتي والشراكات الاستثمارية في المشروعات. " * 10), (31, "إدارة الأزمات وتنويع الاستثمارات لمواجهة المخاطر. " * 10), ) _, a, _ = _best_window(pages, "التمويل الذاتي الشراكات الاستثمارية") _, b, _ = _best_window(pages, "إدارة الأزمات تنويع الاستثمارات") assert a == 5 and b == 31 # ═══════════════════════════════════════════ القائمة = ما استشهد به المتن CREDITS = { "https://a.org/x.pdf": {"author": "العنزي", "year": "2023"}, "https://b.org/y.pdf": {"author": "الغامدي", "year": "2022"}, "https://c.org/z.pdf": {"author": "القحطاني", "year": "2024"}, } CONTENT = [{"cover": "محور", "blocks": [ {"block_type": "paragraph", "paragraphs": ["نص يستشهد بـ (العنزي، 2023، ص. 19) ثم يواصل.", "وهنا (الغامدي، 2022، ص ص. 4-6) في موضع آخر."]}]}] def test_only_the_sources_the_text_cites_reach_the_list(): used = cited_urls(CONTENT, CREDITS) assert used == {"https://a.org/x.pdf", "https://b.org/y.pdf"} assert "https://c.org/z.pdf" not in used def test_a_source_is_matched_whatever_page_the_citation_names(): """رقم الصفحة يختلف من موضع لآخر، فالاسم والسنة هما ما يميّز المصدر.""" content = [{"blocks": [{"paragraphs": ["(العنزي، 2023)"]}]}] assert cited_urls(content, CREDITS) == {"https://a.org/x.pdf"} def test_a_citation_with_no_source_in_this_run_is_named_not_hidden(): content = [{"blocks": [{"paragraphs": ["نص فيه (الحربي، 2021، ص. 3) فقط."]}]}] assert orphan_citations(content, CREDITS) == ["الحربي"] assert orphan_citations(CONTENT, CREDITS) == [] # ═══════════════════════════════════════════ شكل المدخل def test_an_in_text_marker_never_enters_the_list(): """«لا يجوز أن تنتقل صيغة التوثيق داخل المتن إلى قائمة المراجع».""" assert is_in_text_marker("أحمد، 2020، ص. 3") assert is_in_text_marker("(أحمد، 2020، ص. 3)") assert is_in_text_marker("OECD, 2024, p. 55") assert is_in_text_marker("بوبكر ديابي، 2012، ص. 7") def test_a_real_entry_is_not_mistaken_for_a_marker(): assert not is_in_text_marker("أحمد، محمد. (2020). عنوان الكتاب. القاهرة: دار النشر.") assert not is_in_text_marker("IBM. (n.d.). What is artificial intelligence? IBM.") assert not is_in_text_marker("وزارة التعليم. (د.ت). الدليل التنظيمي.") def test_two_shapes_of_one_work_share_a_key(): """نفس الورقة بعنوانين، أحدهما مبتور وأحدهما بلا سنة — مدخل واحد.""" a = "أثر المجالات المعرفية لإدارة المشاريع على جودة المخرجات. (2022). https://x/1" b = "أثر المجالات المعرفية لإدارة المشاريع على جودة المخرجات. (د.ت). https://x/2" assert _work_key(a) != _work_key(b) # السنة تميّز c = "أثر المجالات المعرفية لإدارة المشاريع على جودة المخرجات. (2022). https://x/2" assert _work_key(a) == _work_key(c) # الرابط وحده لا يميّز def test_an_entry_that_is_only_a_link_keeps_its_own_identity(): """صفحة مؤسسية بلا عنوان حقيقي تُميَّز برابطها، وإلا انطوت كلها في مدخل.""" assert _work_key("مرجع https://x.org/0") != _work_key("مرجع https://x.org/1") # ═══════════════════════════════════════════ الحداثة لا تكسر المطابقة def _ref(text, language="ar"): return {"reference": text, "language": language, "kind": "كتاب"} def test_the_recency_floor_is_not_applied_to_a_cited_list(): """«كل مصدر تم الاستشهاد به في المتن يجب أن يظهر في قائمة المراجع» — فحذف القديم من القائمة يصنع بيده الخلل الذي يمنعه.""" import inspect from app.agents.arabic_bag import references # الصياغة بوكيل صارت آخر ملاذ، والأرضية بقيت معها وحدها. assert "drop_stale" in inspect.getsource(references._refs_from_agent) assert "drop_stale" not in inspect.getsource(references.run_references) def test_the_floor_still_applies_when_nothing_was_cited(): floor_refs = [_ref(f"مؤلف{i}، أ. (2024). عنوان.") for i in range(9)] floor_refs.append(_ref("قديم، ب. (2009). عنوان.")) assert len(drop_stale(floor_refs)) == 9 # ═══════════════════════════════════════════ الخطوة نفسها def test_the_references_step_can_no_longer_be_skipped(): """حقيبة شُغِّلت بلا هذه الخطوة خرجت بعشرة استشهادات وصفحة مراجع فارغة.""" from app.pipelines.registry import get, load_all load_all() step = next(s for s in get("arabic_training_bag").steps if s.key == "bag_ar.references") assert step.optional is False assert "bag_ar.content" in step.depends_on assert "bag_ar.citations" in step.depends_on def test_the_references_step_runs_after_the_content_that_feeds_it(): from app.pipelines.registry import get, load_all load_all() keys = [s.key for s in get("arabic_training_bag").steps] assert keys.index("bag_ar.content") < keys.index("bag_ar.references") # ═══════════════════════════════════════════ ما يُعرض على الكاتب def test_a_stale_source_is_still_not_offered_for_citation(): """الحداثة موضعها الاختيار، قبل الاستشهاد، لا القائمة بعده.""" scraped = [{"cover": "م", "sources": [ {"title": "حديث", "url": "https://a.org/x.pdf", "pages": [19, 20]}, {"title": "قديم", "url": "https://b.org/y.pdf", "pages": [3, 4]}]}] credits = {"https://a.org/x.pdf": {"author": "العنزي", "year": "2024"}, "https://b.org/y.pdf": {"author": "القديمي", "year": "2011"}} block = citation_block("م", scraped, credits) assert "العنزي" in block and "القديمي" not in block # والصفحة المعروضة هي صفحة المقطع. assert "ص ص. 19-20" in block @pytest.mark.parametrize("cover_pages,expected", [ ([19, 19], "ص. 19"), ([19, 21], "ص ص. 19-21"), ]) def test_the_offered_citation_names_the_excerpt_s_pages(cover_pages, expected): scraped = [{"cover": "م", "sources": [ {"title": "ت", "url": "https://a.org/x.pdf", "pages": cover_pages}]}] credits = {"https://a.org/x.pdf": {"author": "العنزي", "year": "2024"}} assert expected in citation_block("م", scraped, credits) def test_the_head_of_the_document_reaches_the_extractor_not_the_excerpt(): """المؤلف والسنة على صفحة العنوان، والمقتطف صار يبدأ من وسط الملف.""" import inspect from app.agents.arabic_bag import citations src = inspect.getsource(citations._extract) assert 's.get("head")' in src def test_the_source_record_carries_the_window_and_the_head(): import inspect from app.agents.arabic_bag import sources src = inspect.getsource(sources.run_source_finder) assert "focus=focus" in src assert '"pages": list(pages) if pages else []' in src assert '"head": head' in src def test_nothing_in_the_new_path_invents_a_page(): """«لا يجوز للأداة اختلاق رقم صفحة» — كل رقم يُطبع جاء من المستند. صفحة الويب لا صفحات لها، فلا رقم لها؛ والمستند الذي لم يُستخرج منه شيء لا نافذة له. """ assert pages_for({"pages": [], "page_lengths": []}, 2500) is None assert _best_window([], "أي موضوع") == ("", None, None) web = [{"cover": "م", "sources": [ {"title": "صفحة", "url": "https://w.org/a", "pages": [], "page_lengths": []}]}] block = citation_block("م", web, {"https://w.org/a": {"author": "المالكي", "year": "2024"}}) assert "→ (المالكي، 2024)" in block assert "ص." not in block.rsplit("→", 1)[-1] def test_the_cited_set_survives_a_json_round_trip(): """المحتوى يصل من مخرَج خطوة محفوظ في قاعدة البيانات، لا من الذاكرة.""" revived = json.loads(json.dumps(CONTENT, ensure_ascii=False)) assert cited_urls(revived, CREDITS) == {"https://a.org/x.pdf", "https://b.org/y.pdf"} def test_a_cover_offered_sources_must_cite_at_least_one(): """«طالما المصدر وفقًا للمعايير يبقى نستشهد به في المحور ده».""" from app.agents.arabic_bag.writer import validate_written_cover plan = {"blocks": [{"block_type": "paragraph", "heading": "", "needs_lead_in": False, "needs_closing_line": False}]} silent = {"blocks": [{"block_type": "paragraph", "heading": "", "paragraphs": ["فقرة بلا أي توثيق فيها إطلاقًا."]}]} errs = validate_written_cover(silent, plan, sourced=True) assert any("بلا توثيق واحد" in e for e in errs) voiced = {"blocks": [{"block_type": "paragraph", "heading": "", "paragraphs": ["فقرة فيها (العنزي، 2023، ص. 19)."]}]} assert not any("بلا توثيق واحد" in e for e in validate_written_cover(voiced, plan, sourced=True)) def test_a_cover_with_no_sources_is_not_asked_to_cite(): from app.agents.arabic_bag.writer import validate_written_cover plan = {"blocks": [{"block_type": "paragraph", "heading": "", "needs_lead_in": False, "needs_closing_line": False}]} silent = {"blocks": [{"block_type": "paragraph", "heading": "", "paragraphs": ["فقرة بلا أي توثيق فيها إطلاقًا."]}]} assert not any("بلا توثيق واحد" in e for e in validate_written_cover(silent, plan, sourced=False))