from __future__ import annotations
import hashlib
import os
from pathlib import Path
import sys
from types import ModuleType, SimpleNamespace
import pytest
import project_brain.build.doc_parser as doc_parser_module
from project_brain.build.doc_parser import DocumentParser
from project_brain.build.document_content import (
DocumentContentError,
DocumentContentLimitError,
DocumentContentPolicy,
)
from project_brain.config import Config, ConfigError
from project_brain.graph.models import DocumentNode
def test_stored_content_config_round_trip(tmp_path: Path) -> None:
config_dir = tmp_path / ".botbrain"
config_dir.mkdir()
(config_dir / "config.yaml").write_text(
"documents:\n"
" stored_content:\n"
" include: ['README.md', 'docs/**/*.md']\n"
" exclude: ['docs/private/**']\n"
" max_file_bytes: 1234\n"
" max_total_bytes: 5678\n"
" on_limit: omit\n",
encoding="utf-8",
)
config = Config.load(str(tmp_path))
assert config.document_content_include == ["README.md", "docs/**/*.md"]
assert config.document_content_exclude == ["docs/private/**"]
assert config.document_content_max_file_bytes == 1234
assert config.document_content_max_total_bytes == 5678
assert config.document_content_on_limit == "omit"
config.save(str(tmp_path))
assert Config.load(str(tmp_path)) == config
@pytest.mark.parametrize(
("yaml_value", "field"),
[
("max_file_bytes: 0", "max_file_bytes"),
("max_total_bytes: -1", "max_total_bytes"),
("on_limit: truncate", "on_limit"),
],
)
def test_stored_content_config_rejects_invalid_limits(
tmp_path: Path, yaml_value: str, field: str
) -> None:
config_dir = tmp_path / ".botbrain"
config_dir.mkdir()
(config_dir / "config.yaml").write_text(
f"documents:\n stored_content:\n {yaml_value}\n", encoding="utf-8"
)
with pytest.raises(ConfigError, match=field):
Config.load(str(tmp_path))
def test_stored_content_config_rejects_unsafe_globs_on_load_and_save(
tmp_path: Path,
) -> None:
config_dir = tmp_path / ".botbrain"
config_dir.mkdir()
config_file = config_dir / "config.yaml"
config_file.write_text(
"documents:\n stored_content:\n include: ['../secret.md']\n",
encoding="utf-8",
)
with pytest.raises(ConfigError, match=r"stored_content.*\.\."):
Config.load(str(tmp_path))
config_file.unlink()
config = Config.default()
config.document_content_include = [r"docs\guide.md"]
with pytest.raises(ConfigError, match="POSIX"):
config.save(str(tmp_path))
assert not config_file.exists()
def test_policy_uses_recursive_posix_globs_and_exclude_precedence() -> None:
policy = DocumentContentPolicy(
include=("README.md", "docs/**/*.md"),
exclude=("docs/private/**",),
)
assert policy.should_store("README.md")
assert policy.should_store("docs/guide.md")
assert policy.should_store("docs/design/deep/topic.md")
assert not policy.should_store("docs/private/secret.md")
assert not policy.should_store("src/module.py")
@pytest.mark.parametrize(
"value",
["/absolute.md", "C:/absolute.md", "docs/../secret.md", r"docs\guide.md"],
)
def test_policy_rejects_non_relative_posix_patterns(value: str) -> None:
with pytest.raises(DocumentContentError):
DocumentContentPolicy(include=(value,))
def test_policy_from_config_exposes_aggregate_budget() -> None:
config = Config.default()
config.document_content_include = ["docs/**"]
config.document_content_max_total_bytes = 9000
policy = DocumentContentPolicy.from_config(config)
assert policy.should_store("docs/a.md")
assert policy.max_total_bytes == 9000
def test_selected_document_stores_exact_canonical_content(tmp_path: Path) -> None:
docs = tmp_path / "docs"
docs.mkdir()
path = docs / "guide.md"
content = "# Guide\n\nFirst paragraph.\n\nSecond paragraph.\n"
path.write_text(content, encoding="utf-8")
parser = DocumentParser(DocumentContentPolicy(include=("docs/**",)))
result = parser.parse_file(path, tmp_path)
assert result.document.content == content
assert result.document.content_state == "full"
assert result.document.content_complete is True
assert result.document.content_bytes == len(content.encode("utf-8"))
assert result.document.content_representation == "source_text"
assert result.chunks
assert all(chunk.doc_id == result.document.id for chunk in result.chunks)
assert all(not hasattr(chunk, "content") for chunk in result.chunks)
assert all(section.content == "" for section in result.sections)
def test_unselected_document_keeps_legacy_metadata_only(tmp_path: Path) -> None:
path = tmp_path / "guide.md"
path.write_text("# Guide\n\nText\n", encoding="utf-8")
parser = DocumentParser(DocumentContentPolicy(include=("docs/**",)))
result = parser.parse_file(path, tmp_path)
assert result.document.content is None
assert result.document.content_state == "not_selected"
assert result.document.content_complete is False
assert result.document.content_bytes == 0
assert result.chunks == []
def test_selected_document_limit_errors_without_truncating(tmp_path: Path) -> None:
path = tmp_path / "large.md"
path.write_text("# Large\n" + "x" * 100, encoding="utf-8")
parser = DocumentParser(DocumentContentPolicy(
include=("large.md",), max_file_bytes=32, on_limit="error"
))
with pytest.raises(DocumentContentLimitError, match="max_file_bytes"):
parser.parse_file(path, tmp_path)
def test_parser_revalidates_size_from_the_opened_snapshot(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
path = tmp_path / "race.md"
path.write_text("small", encoding="utf-8")
parser = DocumentParser(DocumentContentPolicy(
include=("race.md",), max_file_bytes=8, on_limit="error",
))
monkeypatch.setattr(
parser,
"_read_source_snapshot",
lambda *_args, **_kwargs: (None, hashlib.md5(b"x" * 64).hexdigest(), 1, 64),
)
with pytest.raises(DocumentContentLimitError, match="64 bytes"):
parser.parse_file(path, tmp_path)
@pytest.mark.parametrize("mutation_point", ["second_fstat", "path_stat"])
def test_streaming_file_digest_rejects_a_changed_file_generation(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
mutation_point: str,
) -> None:
path = tmp_path / "changing.md"
path.write_text("stable body", encoding="utf-8")
real_fstat = os.fstat
real_path_stat = Path.stat
def changed(value: os.stat_result) -> SimpleNamespace:
return SimpleNamespace(
st_dev=value.st_dev,
st_ino=value.st_ino,
st_size=value.st_size,
st_mtime_ns=value.st_mtime_ns + 1,
st_ctime_ns=value.st_ctime_ns,
)
if mutation_point == "second_fstat":
calls = 0
def changing_fstat(fd: int):
nonlocal calls
calls += 1
value = real_fstat(fd)
return changed(value) if calls == 2 else value
monkeypatch.setattr(doc_parser_module.os, "fstat", changing_fstat)
else:
monkeypatch.setattr(
Path,
"stat",
lambda self, *args, **kwargs: changed(
real_path_stat(self, *args, **kwargs)
),
)
with pytest.raises(DocumentContentError, match="changed while"):
DocumentParser.file_digest(path)
def test_conversion_uses_stable_bounded_bytes_not_replaced_live_path(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
path = tmp_path / "race.txt"
original = b"original snapshot\n"
path.write_bytes(original)
parser = DocumentParser(DocumentContentPolicy(
include=("race.txt",), max_file_bytes=32, on_limit="error",
))
def replace_during_conversion(raw: bytes, original_path: Path):
original_path.write_bytes(b"x" * 4096)
return parser._decode_snapshot_text(raw), False
monkeypatch.setattr(
parser, "_convert_snapshot_to_markdown", replace_during_conversion,
)
result = parser.parse_file(path, tmp_path)
assert result.document.content == original.decode("utf-8")
assert result.document.input_md5 == hashlib.md5(original).hexdigest()
assert result.document.content_bytes == len(original)
def test_explicit_omit_marks_oversize_document_without_reading_body(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
path = tmp_path / "large.md"
path.write_text("# Large\n" + "x" * 100, encoding="utf-8")
parser = DocumentParser(DocumentContentPolicy(
include=("large.md",), max_file_bytes=32, on_limit="omit"
))
def fail_body_read(*_args: object, **_kwargs: object) -> None:
raise AssertionError("oversize omit must not load or convert the body")
monkeypatch.setattr(parser, "_read_text", fail_body_read)
monkeypatch.setattr(parser, "_convert_to_markdown", fail_body_read)
result = parser.parse_file(path, tmp_path)
assert result.document.content is None
assert result.document.content_state == "omitted_oversize"
assert result.document.content_complete is False
assert result.chunks == []
assert result.sections == []
def test_non_markdown_oversize_omit_never_invokes_converter(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
path = tmp_path / "large.txt"
raw = b"heading\n" + (b"x" * 256)
path.write_bytes(raw)
parser = DocumentParser(DocumentContentPolicy(
include=("large.txt",), max_file_bytes=32, on_limit="omit",
))
def fail_converter() -> None:
raise AssertionError("MarkItDown must not see an oversize raw file")
monkeypatch.setattr(doc_parser_module, "_get_markitdown", fail_converter)
monkeypatch.setattr(
Path, "read_bytes",
lambda *_args, **_kwargs: (_ for _ in ()).throw(
AssertionError("oversize omit must not call Path.read_bytes")
),
)
monkeypatch.setattr(
Path, "read_text",
lambda *_args, **_kwargs: (_ for _ in ()).throw(
AssertionError("oversize omit must not call Path.read_text")
),
)
result = parser.parse_file(path, tmp_path)
assert result.document.input_md5 == hashlib.md5(raw).hexdigest()
assert result.document.content_state == "omitted_oversize"
assert result.sections == []
assert result.chunks == []
def test_unselected_giant_document_is_streamed_as_metadata_only(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
path = tmp_path / "giant.md"
path.write_text("x" * 100, encoding="utf-8")
parser = DocumentParser(DocumentContentPolicy(include=("docs/**",)))
parser.MAX_METADATA_FILE_BYTES = 32
def fail_body_read(*_args: object, **_kwargs: object) -> None:
raise AssertionError("giant unselected document must not load its body")
monkeypatch.setattr(parser, "_read_text", fail_body_read)
result = parser.parse_file(path, tmp_path)
assert result.document.content_state == "not_selected"
assert result.document.content is None
assert result.document.line_count == 1
assert result.sections == []
def test_long_section_chunks_have_ranges_and_overlap(tmp_path: Path) -> None:
path = tmp_path / "long.md"
paragraphs = [f"Paragraph {index} " + (chr(65 + index) * 590) for index in range(8)]
content = "# Long Section\n\n" + "\n\n".join(paragraphs) + "\n"
path.write_text(content, encoding="utf-8")
parser = DocumentParser(DocumentContentPolicy(include=("long.md",)))
result = parser.parse_file(path, tmp_path)
assert len(result.chunks) >= 4
for chunk in result.chunks:
source = content[chunk.char_start:chunk.char_end]
assert source.strip()
assert not hasattr(chunk, "content_preview")
assert chunk.line_start >= 1
assert chunk.line_end >= chunk.line_start
assert chunk.title == "Long Section"
assert chunk.section_id == result.sections[0].id
assert all(
current.char_start < previous.char_end
for previous, current in zip(result.chunks, result.chunks[1:])
)
def test_chunk_spanning_sections_uses_document_level_metadata(tmp_path: Path) -> None:
path = tmp_path / "short-sections.md"
path.write_text(
"# Guide\n\n## First\nalpha\n\n## Second\nneedle\n",
encoding="utf-8",
)
parser = DocumentParser(DocumentContentPolicy(include=("short-sections.md",)))
result = parser.parse_file(path, tmp_path)
assert len(result.chunks) == 1
assert result.chunks[0].section_id is None
assert result.chunks[0].title == result.document.title
def test_selected_heading_heavy_document_has_bounded_metadata(tmp_path: Path) -> None:
path = tmp_path / "headings.md"
content = "".join(f"## Heading {index}\nvalue {index}\n" for index in range(10_000))
path.write_text(content, encoding="utf-8")
parser = DocumentParser(DocumentContentPolicy(include=("headings.md",)))
result = parser.parse_file(path, tmp_path)
assert len(result.sections) == parser.MAX_SECTION_NODES
assert len(result.document.section_titles) == parser.MAX_SECTION_TITLES
assert len(result.chunks) <= parser.MAX_CHUNKS
assert len(result.chunks) < len(result.sections)
assert result.document.content == content
assert all(section.content == "" for section in result.sections)
assert all(not hasattr(chunk, "content") for chunk in result.chunks)
def test_million_short_lines_keep_snapshot_but_degrade_structure(
tmp_path: Path,
) -> None:
path = tmp_path / "dense.md"
content = "x\n" * 1_000_000
path.write_text(content, encoding="utf-8")
parser = DocumentParser(DocumentContentPolicy(
include=("dense.md",), max_file_bytes=4 * 1024 * 1024,
))
result = parser.parse_file(path, tmp_path)
assert result.document.content == content
assert result.document.line_count == 1_000_000
assert len(result.sections) == 1
assert result.sections[0].line_end == 1_000_000
assert result.sections[0].content == ""
assert len(result.chunks) <= parser.MAX_CHUNKS
def test_document_concept_extraction_is_bounded(tmp_path: Path) -> None:
path = tmp_path / "concepts.md"
path.write_text(
" ".join(f"`Concept{index}`" for index in range(5_000)),
encoding="utf-8",
)
parser = DocumentParser()
result = parser.parse_file(path, tmp_path)
assert len(result.concepts) == parser.MAX_CONCEPT_NODES
def test_extremely_long_heading_cannot_amplify_graph_labels(tmp_path: Path) -> None:
path = tmp_path / "long-heading.md"
content = "# " + ("T" * 1_500_000) + "\n"
path.write_text(content, encoding="utf-8")
parser = DocumentParser(DocumentContentPolicy(include=("long-heading.md",)))
result = parser.parse_file(path, tmp_path)
labels = [
result.document.title,
*result.document.section_titles,
*(section.title for section in result.sections),
*(chunk.title for chunk in result.chunks),
]
assert labels
assert all(len(label) <= parser.MAX_TITLE_CHARS for label in labels)
assert sum(map(len, labels)) <= len(labels) * parser.MAX_TITLE_CHARS
assert result.document.content == content
def test_front_matter_larger_than_limit_is_not_parsed(
monkeypatch: pytest.MonkeyPatch,
) -> None:
parser = DocumentParser()
called = False
def fail_yaml(_value: str) -> object:
nonlocal called
called = True
raise AssertionError("oversize front matter must not reach YAML")
monkeypatch.setattr(doc_parser_module.yaml, "safe_load", fail_yaml)
content = "---\n" + ("x" * (parser.MAX_FRONT_MATTER_BYTES + 1)) + "\n---\nBody"
parser._extract_summary(content)
assert called is False
def test_front_matter_description_requires_string_scalar(
monkeypatch: pytest.MonkeyPatch,
) -> None:
parser = DocumentParser()
monkeypatch.setattr(
doc_parser_module.yaml,
"safe_load",
lambda _value: {"description": ["not", "a", "scalar"]},
)
summary = parser._extract_summary("---\ndescription: ignored\n---\nBody text\n")
assert summary == "Body text"
def test_front_matter_memory_error_is_not_swallowed(
monkeypatch: pytest.MonkeyPatch,
) -> None:
parser = DocumentParser()
def fail_yaml(_value: str) -> object:
raise MemoryError("yaml budget")
monkeypatch.setattr(doc_parser_module.yaml, "safe_load", fail_yaml)
with pytest.raises(MemoryError, match="yaml budget"):
parser._extract_summary("---\ndescription: text\n---\nBody\n")
def test_read_and_conversion_do_not_swallow_memory_error(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
path = tmp_path / "memory.txt"
path.write_text("body", encoding="utf-8")
parser = DocumentParser()
monkeypatch.setattr(
Path, "read_bytes",
lambda *_args, **_kwargs: (_ for _ in ()).throw(MemoryError("read")),
)
with pytest.raises(MemoryError, match="read"):
parser._read_text(path)
class Converter:
def convert(self, _path: str) -> object:
raise MemoryError("convert")
monkeypatch.setattr(doc_parser_module, "_get_markitdown", lambda: Converter())
with pytest.raises(MemoryError, match="convert"):
parser._convert_to_markdown(path)
def test_markitdown_initialization_does_not_swallow_memory_error(
monkeypatch: pytest.MonkeyPatch,
) -> None:
fake_module = ModuleType("markitdown")
class Converter:
def __init__(self) -> None:
raise MemoryError("initialize")
fake_module.MarkItDown = Converter
monkeypatch.setitem(sys.modules, "markitdown", fake_module)
monkeypatch.setattr(doc_parser_module, "_markitdown", None)
with pytest.raises(MemoryError, match="initialize"):
doc_parser_module._get_markitdown()
def test_chunk_cap_keeps_final_window_bounded_at_worst_progress(
monkeypatch: pytest.MonkeyPatch,
) -> None:
parser = DocumentParser()
parser.MAX_CHUNKS = 8
content = "x" * 10_000
document = DocumentNode(
id="doc_bound",
title="Bound",
path="bound.md",
format="markdown",
line_count=1,
md5="digest",
content=content,
content_complete=True,
content_bytes=len(content),
)
target = max(
parser.CHUNK_TARGET_CHARS,
2 * (
(len(content) + parser.MAX_CHUNKS - 1) // parser.MAX_CHUNKS
+ parser.CHUNK_OVERLAP_CHARS
+ 50
),
)
def worst_case_end(
_content: str, start: int, range_end: int, *, target_chars: int | None = None,
) -> int:
return min(range_end, start + int(target_chars or target) // 2)
monkeypatch.setattr(parser, "_chunk_end", worst_case_end)
chunks = parser._build_chunks(content, document, [])
assert len(chunks) <= parser.MAX_CHUNKS
assert max(chunk.char_end - chunk.char_start for chunk in chunks) <= target
def test_document_without_heading_has_implicit_section(tmp_path: Path) -> None:
path = tmp_path / "plain.txt"
path.write_text("first line\nsecond line", encoding="utf-8")
result = DocumentParser().parse_file(path, tmp_path)
assert len(result.sections) == 1
assert result.sections[0].title == "Plain"
assert result.sections[0].line_start == 1
assert result.sections[0].line_end == 2
def test_old_document_dict_gets_content_defaults() -> None:
node = DocumentNode.from_dict({
"id": "doc_old",
"title": "Old",
"path": "old.md",
"format": "markdown",
"line_count": 1,
"md5": "abc",
})
assert node.content is None
assert node.content_state == "not_selected"
assert node.content_complete is False
def test_gbk_encoded_markdown_decodes_correctly(tmp_path: Path) -> None:
"""A GBK-encoded .md file must decode Chinese correctly, not as □ or garbage."""
path = tmp_path / "guide.md"
path.write_text("# 项目文档\n\n这是中文内容\n", encoding="gbk")
result = DocumentParser().parse_file(path, tmp_path)
assert "项目文档" in result.document.title
assert result.document.content_state == "not_selected"
def test_gbk_encoded_txt_decodes_correctly(tmp_path: Path) -> None:
"""A GBK-encoded .txt file must decode Chinese correctly via the unified path."""
path = tmp_path / "notes.txt"
path.write_text("配置说明\n这是GBK编码的中文内容\n", encoding="gbk")
result = DocumentParser().parse_file(path, tmp_path)
assert result.document.title
for section in result.sections:
if section.content:
assert "中文" in section.content or "配置" in section.content
def test_utf8_with_emoji_not_misdecoded_as_gbk(tmp_path: Path) -> None:
"""UTF-8 content with emoji must decode correctly, not as GBK garbage."""
path = tmp_path / "emoji.md"
path.write_text("# Guide 🌍\n\nHello world café résumé\n", encoding="utf-8")
result = DocumentParser().parse_file(path, tmp_path)
assert "Guide" in result.document.title
sections = result.sections
assert any("café" in (s.content or "") or "café" in str(s.title) for s in sections) or \
"🌍" in (result.document.summary or "")
def test_shift_jis_file_does_not_crash(tmp_path: Path) -> None:
"""Shift-JIS content must not crash; it may produce imperfect decoding.
Note: GBK strict decode succeeds on many Shift-JIS byte sequences, so the
GBK fallback layer may produce garbled text for Japanese files. This is a
known limitation of the UTF-8 → GBK fallback strategy: without a BOM or
explicit encoding hint, distinguishing GBK from Shift-JIS is not reliable.
The test only verifies the parser does not crash and still produces a
DocumentNode with metadata.
"""
path = tmp_path / "japanese.txt"
path.write_text("これは日本語のテストです\n", encoding="shift_jis")
result = DocumentParser().parse_file(path, tmp_path)
assert result.document is not None
assert result.document.path == "japanese.txt"
assert result.document.line_count >= 1
def test_tokenizer_json_base64_not_indexed(tmp_path: Path) -> None:
"""A .json file with base64 model weights must not have its body in sections."""
import base64
import json
blob = base64.b64encode(bytes(range(256)) * 20).decode()
data = {"model": {"weights": blob, "vocab_size": 30000}, "vocab": {"hello": 1}}
path = tmp_path / "tokenizer.json"
path.write_text(json.dumps(data), encoding="utf-8")
result = DocumentParser().parse_file(path, tmp_path)
assert result.document.content_state == "omitted_binary"
assert result.document.content_complete is False
assert result.document.content is None
assert result.chunks == []
for section in result.sections:
assert section.content == ""
def test_normal_json_still_indexed(tmp_path: Path) -> None:
"""A normal .json file must still get a section preview for BM25."""
import json
path = tmp_path / "config.json"
path.write_text(json.dumps({"name": "myapp", "version": "1.0"}), encoding="utf-8")
result = DocumentParser().parse_file(path, tmp_path)
assert result.document.content_state == "not_selected"
assert len(result.sections) >= 1
assert any("myapp" in (s.content or "") for s in result.sections)
def test_hex_data_not_indexed(tmp_path: Path) -> None:
"""A file dominated by hex strings must be flagged as binary noise."""
hex_blob = "".join(f"{i:02x}" for i in range(256)) * 20
path = tmp_path / "weights.txt"
path.write_text(f"weights: {hex_blob}\n", encoding="utf-8")
result = DocumentParser().parse_file(path, tmp_path)
assert result.document.content_state == "omitted_binary"
assert result.document.content is None
for section in result.sections:
assert section.content == ""