diff --git a/dokimi/changelog.d/20261126_150000_novelty-walkthrough-spans.md b/dokimi/changelog.d/20261126_150000_novelty-walkthrough-spans.md new file mode 100644 index 000000000..960f3ae26 --- /dev/null +++ b/dokimi/changelog.d/20261126_150000_novelty-walkthrough-spans.md @@ -0,0 +1,10 @@ +### Fixed + +- **`skill novelty` spans and walkthrough match what the commands do** — indented code or a Setext heading may + follow a closed fence, an ATX heading or another Setext heading without a blank line; four-space indented + backticks after a blank line are code, not a fence, and an ATX heading may be indented up to three spaces. + `dangling_fence` now reads the text through `segment`, so a stitched bundle cannot open a fence that + `segment` does not see, and `_stitch` keeps the first line's indentation. Span ids shift for artifacts that + use these forms. The walkthrough now says that `analyze --max-usd` stopped in measurement leaves + `novelty.partial.json`, that sole carriers are in `novelty.json` under `views.sole_carriers` + (not in `annotated.html`), and that `probe` files carry no `run_config`. diff --git a/dokimi/docs/skill-novelty-walkthrough.md b/dokimi/docs/skill-novelty-walkthrough.md index ac8a2aab1..a09336f42 100644 --- a/dokimi/docs/skill-novelty-walkthrough.md +++ b/dokimi/docs/skill-novelty-walkthrough.md @@ -81,7 +81,7 @@ follows the artifact's length and the models. Pass `--max-usd ` to every step model: the run stops once its calls across all roles have cost that much (calls already in flight can overshoot it), and a call with no known price stops it too, since the cap cannot see that spend. A step that stops at the cap writes nothing, except -`atoms`, `probe`, `skill routing --model` and `catalog routing --model`, which save the calls they made as a `partial` result (see +`atoms`, `probe`, `analyze`, `skill routing --model` and `catalog routing --model`, which save the calls they made as a `partial` result (see the list below and [skill-novelty.md](skill-novelty.md)). One measured pair, a 19k-token skill: triage 103 calls, about $1.80; `study` 1,901 calls, about $14.50. @@ -104,9 +104,12 @@ What a stopped run leaves behind depends on the step: finished one: the atom readers and `novelty items` refuse it. A later stopped run replaces an earlier partial file, but never a finished one: if `.partial.json` holds anything other than a partial result, the new one goes to `.partial2.json` (and so on). -- `analyze` keeps nothing. If the measurement is cut short, it stops before its classify and - attribution stages, writes no artifact, and reports how many probe answers were not run. - Raise `--max-usd`, or measure less (a cheaper `--tier` or a lower `--max-atoms`). +- `analyze` keeps nothing as a finished result when the measurement is cut short: it stops before + its classify and attribution stages and writes `novelty.partial.json` (status `partial`, + `partial.stage` `measurement`) with the atoms and the probe answers received, and reports how many + probe answers were not run. Raise `--max-usd`, or measure less (a cheaper `--tier` or a lower + `--max-atoms`). If the cap stops it while the paraphrase or reversal wordings are built, the + partial file holds no answers. - `shorten` writes no candidate table and no `--out` file. Its retention verdicts are stored in `--cache-dir` as each is adjudicated, and the exit message says how many: rerun with a higher `--max-usd` (with no `--max-usd` when the stop is a model with no known price) and the same @@ -176,7 +179,8 @@ knowledge the model got wrong with and without the artifact (`still_missing`), a carries atoms with nothing measured or judged against them (`unscored`). The full rules are in [skill-novelty.md](skill-novelty.md) ("Span attribution"). Two derived lists are where edits start: **dead weight** (dim spans by token cost) and **sole carriers** -(spans that are the only source of something). +(spans that are the only source of something). `annotated.html` does not list them: read +`views.sole_carriers` and `views.dead_weight` in `novelty.json`; `novelty.md` gives their counts. With `--include-resources`, `bundle.by_source` says which *file* carried the knowledge. A reference whose atoms are all `redundant` is a file the model already knows; one full of @@ -221,8 +225,10 @@ The protected-span count is not in `probe` output: it lives in `shorten`'s table If the atoms came from a bundle, put the shortened `SKILL.md` into a copy of the skill directory rather than probing `short/` on its own: `probe` refuses a file set that differs from the one recorded in `atoms.json`. -Two cells compare only when their `run_config` blocks match, which includes the tier, the -probe kinds, `include_resources` and the prompt digest. +A `probe` file carries no `run_config`: two `probe` files compare as the same cell only when you +ran them with the same atoms file, models, probe flags and `--seed`. The `run_config` block (the +tier, the probe kinds, `include_resources` and the prompt digest) is in `analyze`'s `novelty.json`, +and two `analyze` cells compare only when those blocks match. ## What this path does not tell you diff --git a/dokimi/dokimi/novelty/bundle.py b/dokimi/dokimi/novelty/bundle.py index c0b2f992d..714d801d4 100644 --- a/dokimi/dokimi/novelty/bundle.py +++ b/dokimi/dokimi/novelty/bundle.py @@ -613,8 +613,10 @@ def _stitch(files: list[BundleFile]) -> str: offset = 0 for index, item in enumerate(files): header = "" if index == 0 else f"\n\n{BUNDLE_HEADER_PREFIX}{item.role}: {item.path}\n\n" - body = item.text.strip() - marker = dangling_fence(body) + # Leading blank lines go, the first line's indentation stays: it can make the line code. + body = re.sub(r"\A(?:[ \t]*\r?\n)+", "", item.text).rstrip() + # Read in the context it is stitched in: a file after the first has a heading above it. + marker = dangling_fence(header + body) if marker: body += f"\n{marker}" chunk = header + body + "\n" diff --git a/dokimi/dokimi/novelty/spans.py b/dokimi/dokimi/novelty/spans.py index 1d31fdfb2..1d42c979e 100644 --- a/dokimi/dokimi/novelty/spans.py +++ b/dokimi/dokimi/novelty/spans.py @@ -20,6 +20,7 @@ import re from dataclasses import dataclass, field +from functools import partial # Ordered: the first matching rule names the tag, but a span can carry several. _PROTECTION_RULES: list[tuple[str, re.Pattern[str]]] = [ @@ -42,9 +43,10 @@ # The whole run of fence characters: a fence closes only on a run at least as long. # A backtick run followed by another backtick on its line is inline code, not a fence. _FENCE = re.compile(r"^\s*(`{3,}(?!.*`)|~{3,})") -_HEADING = re.compile(r"^(#{1,6})\s+(.*)$") -# A Setext underline: `=` for a level 1 heading, `-` (two or more, a lone `-` is a list item) for level 2. -_SETEXT = re.compile(r"^ {0,3}(=+|-{2,})\s*$") +_HEADING = re.compile(r"^ {0,3}(#{1,6})\s+(.*)$") +# A Setext underline: `=` for a level 1 heading, `-` for level 2; one character is enough, and under a paragraph +# line a lone `-` underlines it (an empty list item cannot interrupt a paragraph). +_SETEXT = re.compile(r"^ {0,3}(=+|-+)\s*$") _INDENTED = re.compile(r"^(?: {4}|\t)") _COMMENT_OPEN = re.compile(r"^ {0,3}``: prose, whatever it starts with - def emit(kind: str, chunk: str, start: int, read: str | None = None) -> None: - stripped = chunk.strip() - if not stripped: - return - # Anchor the trimmed text inside the raw chunk so offsets stay exact. - lead = len(chunk) - len(chunk.lstrip()) - begin = start + lead - spans.append(Span( - id=f"s{len(spans) + 1:04d}", - kind=kind, - text=stripped, - start=begin, - end=begin + len(stripped), - heading_path=tuple(heading_path), - # a comment, or one inside a sentence or list item, is not read as a rule - protection=() if kind == "comment" else protection_tags(_blank_comments(read or stripped, " ")), - )) + emit = partial(_emit_span, spans, heading_path) while i < len(lines): line = lines[i] @@ -372,18 +392,16 @@ def emit(kind: str, chunk: str, start: int, read: str | None = None) -> None: prose_only = i == after_comment and not _COMMENT_OPEN.match(line) - if not prose_only and _FENCE.match(line): - fence = _FENCE.match(line).group(1) # type: ignore[union-attr] - block = [line] - offset += len(line) - i += 1 - while i < len(lines): - block.append(lines[i]) - offset += len(lines[i]) - closed = _closes(lines[i], fence) - i += 1 - if closed: - break + # Indented code is read before a fence: `` ```\n`` after a blank line is code, not an opener. + opener = None if prose_only or _opens_code(lines, i, in_list, fresh) else _FENCE.match(line) + if opener: + in_list = in_list and line.startswith((" ", "\t")) + fence = opener.group(1) + end, closed = _fence_block(lines, i, fence) + dangling = None if closed else fence + block = lines[i:end] + offset += sum(len(x) for x in block) + i = fresh = end emit("code", "".join(block), start) continue @@ -394,13 +412,15 @@ def emit(kind: str, chunk: str, start: int, read: str | None = None) -> None: n_lines = len(lines) in_list = in_list and line.startswith((" ", "\t")) - scaffold = None if prose_only else _scaffold(lines, i, spans, in_list) + scaffold = None if prose_only else _scaffold(lines, i, spans, in_list, fresh) if scaffold: kind, end, level = scaffold if len(lines) > n_lines: after_comment = end chunk = "".join(lines[i:end]) _enter_heading(heading_path, level, chunk) + if kind != "comment": + fresh = end emit(kind, chunk, start) offset += len(chunk) i = end @@ -442,7 +462,7 @@ def emit(kind: str, chunk: str, start: int, read: str | None = None) -> None: # Split on the paragraph with each closed comment blanked (same length), so no cut falls inside one. _emit_pieces("sentence", paragraph, start, hidden_from, emit) - return spans + return spans, dangling def index_atoms(spans: list[Span], atoms: list) -> None: diff --git a/dokimi/scripts/growth_baseline.json b/dokimi/scripts/growth_baseline.json index 2ccd7c396..52e89aee5 100644 --- a/dokimi/scripts/growth_baseline.json +++ b/dokimi/scripts/growth_baseline.json @@ -46,7 +46,6 @@ "dokimi/novelty/probes.py::build_probe_set": {"complexity": 12}, "dokimi/novelty/probes.py::check_wording": {"complexity": 13}, "dokimi/novelty/report.py::render_novelty_markdown": {"complexity": 15}, - "dokimi/novelty/spans.py::segment": {"complexity": 13}, "dokimi/orchestrator/pipeline.py::EvaluationPipeline.run": {"complexity": 11}, "dokimi/plugins.py::create_plugin": {"complexity": 11}, "dokimi/process.py::_select_pipes": {"complexity": 13}, diff --git a/dokimi/tests/test_novelty_journey.py b/dokimi/tests/test_novelty_journey.py index e09057dd3..43e0ce151 100644 --- a/dokimi/tests/test_novelty_journey.py +++ b/dokimi/tests/test_novelty_journey.py @@ -356,3 +356,41 @@ def failing_measurement(*args, **kwargs): with pytest.raises(SystemExit) as exc: cli.main() assert exc.value.code == message + + +_WALKTHROUGH = Path(__file__).resolve().parents[1] / "docs" / "skill-novelty-walkthrough.md" + + +def test_walkthrough_says_a_capped_analyze_leaves_novelty_partial_json(): + """#974: `analyze --max-usd` stopped in measurement writes `novelty.partial.json`, no `novelty.json`.""" + text = _WALKTHROUGH.read_text(encoding="utf-8") + item = text[text.index("- `analyze` keeps nothing as a finished result"):] + item = item[:item.index("\n- ")] + assert "novelty.partial.json" in item and "writes no artifact" not in item + + +def test_walkthrough_names_where_the_sole_carriers_are(): + """#974: `annotated.html` holds no sole-carrier list; `novelty.json` has `views.sole_carriers`.""" + text = _WALKTHROUGH.read_text(encoding="utf-8") + section = text[text.index("## 6. Read the view"):text.index("## What this path does not")] + assert "`views.sole_carriers`" in section and "`novelty.json`" in section + + +def test_a_probe_file_has_no_run_config_and_the_walkthrough_says_so(tmp_path, monkeypatch): + """#974: the walkthrough must not ask readers to compare a `run_config` that `probe` never writes.""" + from tests.test_novelty_atoms_sample import _capped_atoms_json, _cli + + skill, atoms_json, _ = _capped_atoms_json(tmp_path, monkeypatch) + out = tmp_path / "p.json" + _cli(monkeypatch, "probe", "--artifact", f"skill:{skill}", "--atoms", str(atoms_json), + "--concurrency", "1", "--no-paraphrase", "--no-reversal", "--out", str(out)) + assert "run_config" not in json.loads(out.read_text()) + assert "A `probe` file carries no `run_config`" in _WALKTHROUGH.read_text(encoding="utf-8") + + +def test_walkthrough_cap_summary_lists_analyze_among_the_steps_that_keep_a_partial_result(): + """#974: `analyze` saves `novelty.partial.json`, so the cap paragraph must not say it writes nothing.""" + text = _WALKTHROUGH.read_text(encoding="utf-8") + paragraph = text[text.index("A step that stops at the cap writes nothing"):] + paragraph = paragraph[:paragraph.index("\n\n")] + assert "`analyze`" in paragraph.split("except", 1)[1] diff --git a/dokimi/tests/test_novelty_spans.py b/dokimi/tests/test_novelty_spans.py index 152ba640d..65ac5c683 100644 --- a/dokimi/tests/test_novelty_spans.py +++ b/dokimi/tests/test_novelty_spans.py @@ -5,6 +5,8 @@ from __future__ import annotations +import pytest + from dokimi.novelty.atoms import Atom from dokimi.novelty.spans import ( dangling_fence, @@ -158,7 +160,7 @@ def test_setext_underline_is_not_taken_from_a_rule_a_list_or_frontmatter(): """#973: `---` after a list item, a lone `-`, a rule after a rule and a frontmatter closer underline nothing.""" assert _kinds("- item\n---\n")[0] == ("list_item", "- item") assert [k for k, _ in _kinds("---\n\n---\n")] == ["sentence", "sentence"] - assert _kinds("Text\n-\n")[0][0] != "heading" + assert _kinds("- item\n-\n")[0] == ("list_item", "- item") front = segment("---\nname: x\n---\n\nKeep it.\n") assert "heading" not in [s.kind for s in front] @@ -435,3 +437,298 @@ def test_an_indented_comment_does_not_break_the_paragraph_it_continues(): """#973: ` ` (four spaces) is paragraph text, so `more\\n---` underlines the whole paragraph.""" spans = segment("Text\n \nmore\n---\n") assert [s.kind for s in spans] == ["heading"] + + +_FRONT = "---\nname: s\ndescription: Use when operating the valve.\n---\n\n" + + +def test_a_setext_heading_is_one_heading_span_like_its_atx_form(): + """#974: `Valve setup. Quick reference` over `====` is not split into sentences.""" + atx = segment("# Valve setup. Quick reference\n\nThe valve opens clockwise.\n") + setext = segment("Valve setup. Quick reference\n============================\n\n" + "The valve opens clockwise.\n") + assert [s.kind for s in setext] == [s.kind for s in atx] == ["heading", "sentence"] + assert setext[1].heading_path == ("Valve setup. Quick reference",) + + +def test_a_dash_underline_is_a_level_two_setext_heading(): + """#974: a `---` underline makes a level-two heading span, like `##`.""" + spans = segment("# Top\n\nSub title. More\n---\n\nBody text.\n") + assert [s.kind for s in spans] == ["heading", "heading", "sentence"] + assert spans[2].heading_path == ("Top", "Sub title. More") + + +def test_front_matter_closing_dashes_do_not_underline_the_last_field(): + """#974: the closing `---` of front matter is not a Setext underline.""" + spans = segment(_FRONT + "The valve opens clockwise.\n") + assert all(s.kind != "heading" for s in spans) + assert segment("---\nname: s\n---\n\nHi there.\n")[0].kind != "heading" + + +def test_dashes_under_a_field_line_that_is_not_front_matter_underline_it(): + """#974: only a leading `---` opens front matter; `a: b` over `---` is a heading.""" + spans = segment("a: b\n---\n\nBody.\n") + assert [s.kind for s in spans] == ["heading", "sentence"] + assert spans[1].heading_path == ("a: b",) + assert segment("") == [] + + +def test_a_setext_heading_or_indented_code_may_follow_a_closed_fence_directly(): + """#974: a closing fence ends a block, so the next line may start one.""" + spans = segment("```\nexample\n```\nTitle. More\n=====\n\nBody.\n") + assert [s.kind for s in spans] == ["code", "heading", "sentence"] + assert spans[2].heading_path == ("Title. More",) + assert [s.kind for s in segment("```\nx\n```\n code. More\n")] == ["code", "code"] + + +def test_a_fence_after_a_list_continuation_and_indented_code_is_seen_alike(): + """#974: `dangling_fence` reads a list item's continuation as `segment` does.""" + text = "- item\n continuation\n\n ```\n example\n" + assert [s.kind for s in segment(text)] == ["list_item", "code"] # the fence is open in a list + assert dangling_fence(text) == "```" + assert dangling_fence("- item\n continuation\n```\nx\n") == "```" + + +def test_indented_code_with_many_blank_lines_is_one_span(): + """#974: a long indented block full of blank lines is one span, found in linear time.""" + body = " a\n" + "\n" * 3000 + " b\n" + spans = segment("Intro.\n\n" + body + "\nAfter.\n") + assert [s.kind for s in spans] == ["sentence", "code", "sentence"] + + +class _CountingLine(str): + """A line that counts how often its text is inspected.""" + + reads = 0 + + def strip(self, *args): + _CountingLine.reads += 1 + return super().strip(*args) + + +def test_block_end_does_bounded_work_over_many_blank_lines(): + """#974: a run of n blank lines is skipped once, not rescanned from each blank line.""" + from dokimi.novelty.spans import _INDENTED, _block_end + + n = 2000 + lines = [_CountingLine(row) for row in [" a\n"] + ["\n"] * n + [" b\n"]] + _CountingLine.reads = 0 + assert _block_end(lines, 0, _INDENTED.match) == len(lines) + assert _CountingLine.reads < 4 * len(lines) + + +def test_a_rule_after_a_blank_line_or_a_list_item_is_not_a_setext_underline(): + """#974: `---` after a blank line or a list item is no Setext underline.""" + assert [s.kind for s in segment("Text here.\n\n---\n\nMore text.\n")] == [ + "sentence", "sentence", "sentence"] + assert [s.kind for s in segment("- item\n---\n")] == ["list_item", "sentence"] + + +def test_four_space_indented_code_is_one_code_span_like_a_fence(): + """#974: `Open the valve. Close the valve.` indented four spaces is not two sentences.""" + fenced = segment("Intro.\n\n```\nOpen the valve. Close the valve.\n```\n\nEnd.\n") + indented = segment("Intro.\n\n Open the valve. Close the valve.\n\nEnd.\n") + assert [s.kind for s in indented] == [s.kind for s in fenced] == ["sentence", "code", "sentence"] + assert indented[1].text == "Open the valve. Close the valve." + + +def test_indented_code_runs_over_blank_lines_and_a_tab_opens_it(): + """#974: indented code is one span over blank lines, and a tab opens it.""" + spans = segment("Intro.\n\n\tone\n\n\ttwo\n\nEnd.\n") + assert [s.kind for s in spans] == ["sentence", "code", "sentence"] + assert "one" in spans[1].text and "two" in spans[1].text + + +def test_an_indented_line_is_not_code_inside_a_list_or_a_paragraph(): + """#974: an indented line in a paragraph or a list stays prose.""" + paragraph = segment("Intro text.\n Still the paragraph.\n") + assert [s.kind for s in paragraph] == ["sentence", "sentence"] + assert [s.kind for s in segment("- item\n\n More of the item.\n")] == ["list_item", "sentence"] + + +def test_indented_code_at_the_start_of_the_text_is_code(): + """#974: indented code at the start of the text is a code span.""" + assert [s.kind for s in segment(" x = 1\n")] == ["code"] + + +def test_segment_offsets_hold_for_setext_and_indented_code(): + """#974: span offsets reconstruct the text for Setext and indented code.""" + text = "Title. Sub\n=====\n\n code. line\n\nEnd here.\n" + for span in segment(text): + assert text[span.start:span.end] == span.text + + +def test_dangling_fence_agrees_with_segment_on_a_backtick_line_in_indented_code(): + """#974: a stitched bundle must not read an indented fence inside indented code as an opener.""" + from dokimi.novelty.bundle import BundleFile, _stitch + + text = _stitch([BundleFile("SKILL.md", "entrypoint", "# Skill\n\n example\n ```"), + BundleFile("references/r.md", "reference", "Reference sentence.")]) + spans = segment(text) + assert dangling_fence("# Skill\n\n example\n ```") is None + assert not any("Reference sentence." in s.text and s.kind == "code" for s in spans) + + +def test_stitch_reads_a_reference_with_front_matter_in_the_context_of_its_heading(): + """#974: alone `---` after `name: ref` is front matter, stitched it is a Setext underline: no fence is left open.""" + from dokimi.novelty.bundle import BundleFile, _stitch + + reference = "---\n\nname: ref\n---\n ```\n example" + text = _stitch([BundleFile("SKILL.md", "entrypoint", "# Skill"), + BundleFile("references/a.md", "reference", reference), + BundleFile("references/b.md", "reference", "Reference sentence.")]) + assert dangling_fence(reference) == "```" + assert not any("Reference sentence." in s.text and s.kind == "code" for s in segment(text)) + assert [s.kind for s in segment(text)][-1] == "sentence" + + +def test_a_setext_heading_straight_after_an_atx_heading_is_a_heading(): + """#974: `Title` over `===` right under `# Top` is a heading span, as `# Title` would be.""" + spans = segment("# Top\nValve setup. Quick reference\n===\n\nBody.\n") + assert [s.kind for s in spans] == ["heading", "heading", "sentence"] + assert spans[2].heading_path == ("Valve setup. Quick reference",) + + +def test_indented_code_straight_after_a_heading_is_one_code_span(): + """#974: indented code under a heading needs no blank line, like a fence there.""" + spans = segment("# Setup\n Open the valve. Close the valve.\n") + assert [s.kind for s in spans] == ["heading", "code"] + + +def test_a_setext_heading_may_wrap_over_several_lines(): + """#974: `Valve setup.` / `Quick reference` over `===` is one heading span.""" + spans = segment("Valve setup.\nQuick reference\n===\n\nBody.\n") + assert [s.kind for s in spans] == ["heading", "sentence"] + assert spans[0].text == "Valve setup.\nQuick reference\n===" + assert spans[1].heading_path == ("Valve setup. Quick reference",) + + +def test_indented_code_that_opens_with_backticks_ends_with_its_indentation(): + """#974: ` ```` after a blank line is indented code, not a fence that swallows the next text.""" + spans = segment("# Setup\n\n ```\n Open the valve. Close the valve.\n\nEnd.\n") + assert [s.kind for s in spans] == ["heading", "code", "sentence"] + assert dangling_fence("# Setup\n\n ```\n Open the valve. Close the valve.\n") is None + + +def test_a_heading_or_indented_code_may_follow_a_setext_heading_directly(): + """#974: a completed Setext heading ends its block, as an ATX heading does.""" + spans = segment("Top\n===\nSub title. More\n---\n\nBody.\n") + assert [s.kind for s in spans] == ["heading", "heading", "sentence"] + assert spans[2].heading_path == ("Top", "Sub title. More") + spans = segment("Setup\n=====\n Open the valve. Close the valve.\n") + assert [s.kind for s in spans] == ["heading", "code"] + + +def test_a_bundle_that_starts_with_indented_code_keeps_it_one_code_span(): + """#974: `_stitch` must not strip the indentation that makes the first line code.""" + from dokimi.novelty.bundle import BundleFile, _stitch + + text = _stitch([BundleFile("SKILL.md", "entrypoint", " Open the valve. Close the valve.\n")]) + assert [s.kind for s in segment(text)] == ["code"] + assert [s.kind for s in segment(_stitch([BundleFile("SKILL.md", "entrypoint", "\n\n x\n")]))] \ + == ["sentence"] + + +def test_an_atx_heading_may_be_indented_up_to_three_spaces(): + """#974: ` # Setup` is a heading, also as the first line of a stitched file.""" + from dokimi.novelty.bundle import BundleFile, _stitch + + text = _stitch([BundleFile("SKILL.md", "entrypoint", " # Setup\n\nBody.\n")]) + spans = segment(text) + assert [s.kind for s in spans] == ["heading", "sentence"] + assert spans[1].heading_path == ("Setup",) + assert [s.kind for s in segment(" # Setup\n")] == ["code"] + + +def test_a_setext_underline_with_crlf_line_endings_is_an_underline(): + """#974: `Setup\\r\\n=====\\r\\n` is one heading and the stitched reference stays apart.""" + from dokimi.novelty.bundle import BundleFile, _stitch + + source = "Setup\r\n=====\r\n ```\r\n example\r\n" + assert [s.kind for s in segment(source)] == ["heading", "code"] + assert dangling_fence(source) is None + text = _stitch([BundleFile("SKILL.md", "entrypoint", source), + BundleFile("references/r.md", "reference", "Reference sentence.")]) + assert not any("Reference sentence." in s.text and s.kind == "code" for s in segment(text)) + + +def test_a_bare_rule_is_not_a_completed_heading_for_the_next_indented_line(): + """#974: `---` then `example` then indented backticks: `segment` sees a paragraph, not code.""" + from dokimi.novelty.bundle import BundleFile, _stitch + + source = "---\n example\n ```\n content\n" + assert dangling_fence(source) == "```" + text = _stitch([BundleFile("SKILL.md", "entrypoint", source), + BundleFile("references/r.md", "reference", "Reference sentence.")]) + spans = segment(text) + assert not any("Reference sentence." in s.text and s.kind == "code" for s in spans) + assert any(s.text == "Reference sentence." for s in spans) + + +def test_an_indented_empty_atx_heading_is_a_heading_and_indented_code_after_it_is_code(): + """#974: ` #` is an empty heading, so the indented fence under it is code and nothing stays open.""" + from dokimi.novelty.bundle import BundleFile, _stitch + + source = " #\n ```\n example\n" + assert [s.kind for s in segment(source)] == ["heading", "code"] + assert dangling_fence(source) is None + spans = segment(_stitch([BundleFile("SKILL.md", "entrypoint", source), + BundleFile("references/r.md", "reference", "Reference sentence.")])) + assert any(s.text == "Reference sentence." and s.kind == "sentence" for s in spans) + + +@pytest.mark.parametrize("item", ["-", "1.", "*\r"]) +def test_an_empty_list_item_is_read_alike_by_segment_and_dangling_fence(item): + """An empty list item opens a list in both, so the indented fence after it is closed.""" + from dokimi.novelty.bundle import BundleFile, _stitch + + source = f"Steps:\n\n{item}\n\n ```\n example" + assert dangling_fence(source) == "```" + spans = segment(_stitch([BundleFile("SKILL.md", "entrypoint", source), + BundleFile("references/r.md", "reference", "Reference sentence.")])) + assert ("heading", "## reference: references/r.md") in [(s.kind, s.text) for s in spans] + assert any(s.kind == "sentence" and s.text == "Reference sentence." for s in spans) + + +@pytest.mark.parametrize("opener", ["```yaml\nname: x", "- item", "# Title", "| a | b |"]) +def test_a_structural_line_ends_the_setext_lookahead(opener): + """A fence, list item, ATX heading or table row under a paragraph line is no Setext text.""" + spans = segment("Intro line\n" + opener + "\n---\nother: y\n```\n\nBody.\n") + assert (spans[0].kind, spans[0].text) == ("sentence", "Intro line") + assert all(s.kind != "heading" or s.text.startswith("#") for s in spans) + + +def test_a_blockquoted_rule_over_a_thematic_break_stays_a_prefilter_claim(): + """`trace prefilter` keeps a `>` rule over `---` as a claim, not as the next claim's heading.""" + from dokimi.context.prefilter import claims_from_guidance + + text = "> Never run `git push --force` on main.\n---\n\nAlways run `make test` first.\n" + assert [(c.text, c.heading) for c in claims_from_guidance(text)] == [ + ("> Never run `git push --force` on main.", ""), ("Always run `make test` first.", "")] + text = "\n---\n\n## Rules\n\nAlways run `make test` first.\n" + assert [c.heading for c in claims_from_guidance(text)] == ["Rules"] + assert not any(s.kind == "heading" for s in segment("Text\n> quoted\n---\n\nBody.\n")) + + +def test_a_fence_after_a_lazy_list_continuation_is_read_alike_by_segment_and_dangling_fence(): + """#974: `outside` continues the item, so `segment` opens the backtick line as a fence and so does `dangling_fence`.""" + from dokimi.novelty.bundle import BundleFile, _stitch + + source = "- item\n\n continuation\noutside\n\n ```\n example" + assert dangling_fence(source) == "```" + spans = segment(_stitch([BundleFile("SKILL.md", "entrypoint", source), + BundleFile("references/r.md", "reference", "Reference sentence.")])) + assert any(s.kind == "sentence" and s.text == "Reference sentence." for s in spans) + + +def test_a_two_space_continuation_paragraph_keeps_the_list_open_for_the_next_indented_one(): + """#974: ` continuation.` belongs to the item, so the four-space paragraph after it is no code block.""" + spans = segment("- item\n\n continuation.\n\n Alpha. Beta.\n") + assert "code" not in [s.kind for s in spans] + + +def test_a_single_hyphen_under_a_paragraph_line_is_a_level_two_setext_heading(): + """`Setup` over a lone `-` is a heading: an empty list item cannot interrupt a paragraph.""" + spans = segment("Setup\n-\n\nNever delete the database.\n") + assert [s.kind for s in spans] == ["heading", "sentence"] + assert spans[1].heading_path == ("Setup",)