From a2a8bce2e9b84f6116576bce127a27601948e3a5 Mon Sep 17 00:00:00 2001 From: vchamarthi <123653452+vchamarthi@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:32:08 -0600 Subject: [PATCH 1/8] fix(novelty): Setext and indented code are one span; fix the guide A Setext heading and four-space indented code were split into sentence spans, so `analyze --estimate-only` counted extra spans. The walkthrough also said `analyze` writes no artifact when the cap stops measurement (it writes `novelty.partial.json`), sent readers to `annotated.html` for sole carriers (they are in `novelty.json`), and asked them to compare a `run_config` that `probe` files do not carry. Fixes #974 Signed-off-by: vchamarthi <123653452+vchamarthi@users.noreply.github.com> --- ...261126_150000_novelty-walkthrough-spans.md | 9 + dokimi/docs/skill-novelty-walkthrough.md | 20 ++- dokimi/dokimi/novelty/bundle.py | 3 +- dokimi/dokimi/novelty/spans.py | 156 ++++++++++++++++-- dokimi/tests/test_novelty_journey.py | 38 +++++ dokimi/tests/test_novelty_spans.py | 132 +++++++++++++++ 6 files changed, 332 insertions(+), 26 deletions(-) create mode 100644 dokimi/changelog.d/20261126_150000_novelty-walkthrough-spans.md 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 0000000000..a8475a39ab --- /dev/null +++ b/dokimi/changelog.d/20261126_150000_novelty-walkthrough-spans.md @@ -0,0 +1,9 @@ +### Fixed + +- **`skill novelty` spans and walkthrough match what the commands do** — a Setext heading + (`Title` over `====` or `----`) is one heading span and a run of four-space or tab indented lines + after a blank line, outside a list, is one code span, so `analyze` and `--estimate-only` no + longer count their sentences as extra spans (and 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 d0ff8b7ef1..b11354b881 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 c0b2f992d5..7de8e7b13f 100644 --- a/dokimi/dokimi/novelty/bundle.py +++ b/dokimi/dokimi/novelty/bundle.py @@ -613,7 +613,8 @@ 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() + # 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() marker = dangling_fence(body) if marker: body += f"\n{marker}" diff --git a/dokimi/dokimi/novelty/spans.py b/dokimi/dokimi/novelty/spans.py index e4add3e8dd..2c13c971c3 100644 --- a/dokimi/dokimi/novelty/spans.py +++ b/dokimi/dokimi/novelty/spans.py @@ -44,6 +44,9 @@ _FENCE = re.compile(r"^\s*(`{3,}(?!.*`)|~{3,})") _HEADING = re.compile(r"^(#{1,6})\s+(.*)$") _LIST_ITEM = re.compile(r"^\s*(?:[-*+]|\d+[.)])\s+") +# A Setext underline: a run of `=` (level 1) or `-` (level 2) under a line of text. +_SETEXT = re.compile(r"^ {0,3}(=+|-+)[ \t]*$") +_INDENTED = (" ", "\t") _TABLE_ROW = re.compile(r"^\s*\|.*\|\s*$") # Sentence split on terminal punctuation followed by whitespace + a capital/backtick. # Deliberately crude: over-splitting costs a little attribution granularity, while a @@ -136,27 +139,131 @@ def dangling_fence(text: str) -> str | None: fence-line parity, or the two disagree and the next text is swallowed into one code span. """ marker: str | None = None - for line in text.splitlines(): - if marker is None: - opened = _FENCE.match(line) - marker = opened.group(1) if opened else None - elif _closes(line, marker): - marker = None + lines = text.splitlines() + in_list = False + i = 0 + while i < len(lines): + line = lines[i] + i += 1 + if marker is not None: + marker = None if _closes(line, marker) else marker + continue + in_list = in_list and not _leaves_list(line) + code_end = _indented_code_end(lines, i - 1, in_list) + if code_end: # a fence line inside indented code is content, as in segment + i = code_end + continue + opened = _FENCE.match(line) + if opened: + marker = opened.group(1) + continue + in_list = in_list or bool(_LIST_ITEM.match(line)) return marker +def _indented_ahead(lines: list[str], i: int) -> bool: + """Whether the blank line ``i`` is followed, after more blank lines, by an indented line.""" + for row in lines[i:]: + if row.strip(): + return row.startswith(_INDENTED) + return False + + +def _fence_end(lines: list[str], i: int) -> int: + """The index one past the fenced block that opens at line ``i``: its closing fence, or the end.""" + opened = _FENCE.match(lines[i]) + fence = opened.group(1) if opened else "```" + for end in range(i + 1, len(lines)): + if _closes(lines[end], fence): + return end + 1 + return len(lines) + + +def _front_matter_end(lines: list[str]) -> int: + """The index of the closing ``---`` of front matter, which underlines nothing; 0 without one. + + Front matter is a leading ``---`` and lines of ``key: value`` up to the next ``---``; a + blank line or a line without a colon in between makes the first ``---`` a rule instead. + """ + if not lines or lines[0].strip() != "---": + return 0 + for n in range(1, len(lines)): + if lines[n].strip() == "---": + return n + if ":" not in lines[n]: + return 0 + return 0 + + +def _leaves_list(line: str) -> bool: + """Whether ``line`` is text outside a list: not blank, not indented, not a list item.""" + return bool(line.strip()) and not line.startswith(_INDENTED) and not _LIST_ITEM.match(line) + + +def _block_start(lines: list[str], i: int) -> bool: + """Whether a block may start at line ``i``: the first line, or after a blank line, a heading or an underline.""" + before = lines[i - 1] + return i == 0 or not before.strip() or bool(_HEADING.match(before) or _SETEXT.match(before)) + + +def _indented_code_end(lines: list[str], i: int, in_list: bool) -> int: + """The index one past the indented code block that starts at line ``i``, or 0 when none does. + + A block opens on a line indented four spaces or a tab that follows a blank line (or the + start of the text) outside a list, and runs over blank lines up to the last indented line. + """ + line = lines[i] + if in_list or not line.strip() or not line.startswith(_INDENTED) \ + or not _block_start(lines, i): + return 0 + end = i + while end < len(lines): + row = lines[end] + if row.strip() and not row.startswith(_INDENTED): + break + if not row.strip() and not _indented_ahead(lines, end): + break + end += 1 + return end + + +def _setext(lines: list[str], i: int, front: int) -> tuple[int, int]: + """``(level, end)`` when lines ``i`` up to ``end`` are a Setext heading, else ``(0, i)``. + + The text is one or more lines of a paragraph over an underline of ``=`` (level 1) or ``-`` + (level 2). ``front`` is the index of the closing ``---`` of front matter, which underlines + nothing. + """ + structural = (_HEADING, _FENCE, _TABLE_ROW, _LIST_ITEM) + line = lines[i] + if not line.strip() or line.startswith(_INDENTED) or _SETEXT.match(line) \ + or not _block_start(lines, i) or any(rule.match(line) for rule in structural): + return 0, i + for k in range(i + 1, len(lines)): + row = lines[k] + if _SETEXT.match(row): + return (0, i) if k == front else (1 if row.lstrip().startswith("=") else 2, k + 1) + if not row.strip() or any(rule.match(row) for rule in structural): + break + return 0, i + + def segment(text: str) -> list[Span]: """Split artifact text into spans in document order. Fenced code blocks stay whole (splitting them would produce spans that are not independently meaningful), table rows and list items are one span each, and prose - paragraphs are split into sentences. + paragraphs are split into sentences. A Setext heading (lines of text over a run of + ``=`` or ``-``) is one heading span like its ``#`` form, and a run of lines indented four + spaces or a tab after a blank line or a heading, outside a list, is one code span like a fence. """ spans: list[Span] = [] heading_path: list[str] = [] lines = text.splitlines(keepends=True) offset = 0 i = 0 + in_list = False + front = _front_matter_end(lines) def emit(kind: str, chunk: str, start: int) -> None: stripped = chunk.strip() @@ -178,22 +285,34 @@ def emit(kind: str, chunk: str, start: int) -> None: while i < len(lines): line = lines[i] start = offset + in_list = in_list and not _leaves_list(line) + + code_end = _indented_code_end(lines, i, in_list) + if code_end: + block = lines[i:code_end] + offset += sum(len(row) for row in block) + i = code_end + emit("code", "".join(block), start) + continue if _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 + end = _fence_end(lines, i) + block = lines[i:end] + offset += sum(len(row) for row in block) + i = end emit("code", "".join(block), start) continue + level, end = _setext(lines, i, front) + if level: + block = lines[i:end] + del heading_path[level - 1:] + heading_path.append(" ".join(row.strip() for row in block[:-1])) + offset += sum(len(row) for row in block) + i = end + emit("heading", "".join(block), start) + continue + heading = _HEADING.match(line) if heading: level, title = len(heading.group(1)), heading.group(2).strip() @@ -222,6 +341,7 @@ def emit(kind: str, chunk: str, start: int) -> None: offset += len(lines[i]) i += 1 emit("list_item", "".join(block), start) + in_list = True continue if not line.strip(): diff --git a/dokimi/tests/test_novelty_journey.py b/dokimi/tests/test_novelty_journey.py index e09057dd33..43e0ce151b 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 df3b4133d0..7318b1553b 100644 --- a/dokimi/tests/test_novelty_spans.py +++ b/dokimi/tests/test_novelty_spans.py @@ -139,3 +139,135 @@ def test_span_summary_indexes_every_atom_so_its_atom_set_is_never_capped(): summary = span_summary(spans, atoms) assert (summary["capped_atom_set"], summary["n_atoms_indexed"]) == (False, 3) assert span_summary(spans)["n_atoms_indexed"] is None + + +_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 not segment("---\nname: s\n---\n\nHi there.\n")[0].kind == "heading" + + +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_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_a_leading_rule_is_not_front_matter(): + """#974: `---` then a blank line is a rule; the later `---` can underline a title.""" + spans = segment("---\n\nTitle. More\n---\n\nBody.\n") + assert [s.kind for s in spans] == ["sentence", "heading", "sentence"] + assert spans[2].heading_path == ("Title. More",) From b00f5da3bee36841c2cd285bb6f2095158c722b8 Mon Sep 17 00:00:00 2001 From: vchamarthi <123653452+vchamarthi@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:29:05 -0600 Subject: [PATCH 2/8] fix(novelty): spans scan list items, fences and code blocks alike dangling_fence now skips a list item's continuation lines as segment does, so a fence opened after one is reported. A Setext heading or indented code may start right after a closed code block. Indented code is found in one pass, and the block-start check no longer reads lines[-1] at the first line. The front-matter and list-continuation cases get tests. Signed-off-by: vchamarthi <123653452+vchamarthi@users.noreply.github.com> --- dokimi/dokimi/novelty/spans.py | 83 +++++++++++++++++------------ dokimi/scripts/growth_baseline.json | 2 +- dokimi/tests/test_novelty_spans.py | 54 ++++++++++++++++++- 3 files changed, 102 insertions(+), 37 deletions(-) diff --git a/dokimi/dokimi/novelty/spans.py b/dokimi/dokimi/novelty/spans.py index 2c13c971c3..70140ba850 100644 --- a/dokimi/dokimi/novelty/spans.py +++ b/dokimi/dokimi/novelty/spans.py @@ -141,32 +141,38 @@ def dangling_fence(text: str) -> str | None: marker: str | None = None lines = text.splitlines() in_list = False + fresh = 0 # the index where a code block last ended: a new block may start there i = 0 while i < len(lines): line = lines[i] i += 1 if marker is not None: marker = None if _closes(line, marker) else marker + if marker is None: + fresh = i continue in_list = in_list and not _leaves_list(line) - code_end = _indented_code_end(lines, i - 1, in_list) + code_end = _indented_code_end(lines, i - 1, in_list, fresh) if code_end: # a fence line inside indented code is content, as in segment - i = code_end + i = fresh = code_end continue opened = _FENCE.match(line) if opened: marker = opened.group(1) continue - in_list = in_list or bool(_LIST_ITEM.match(line)) + if _LIST_ITEM.match(line): # its continuation lines belong to it, as in segment + i = _list_item_end(lines, i) + in_list = True return marker -def _indented_ahead(lines: list[str], i: int) -> bool: - """Whether the blank line ``i`` is followed, after more blank lines, by an indented line.""" - for row in lines[i:]: - if row.strip(): - return row.startswith(_INDENTED) - return False +def _list_item_end(lines: list[str], i: int) -> int: + """The index one past the list item whose first line is ``i - 1``: its indented follow-on lines.""" + while i < len(lines) and lines[i].strip() and not _LIST_ITEM.match(lines[i]) \ + and not _HEADING.match(lines[i]) and not _FENCE.match(lines[i]) \ + and lines[i].startswith((" ", "\t")): + i += 1 + return i def _fence_end(lines: list[str], i: int) -> int: @@ -200,13 +206,19 @@ def _leaves_list(line: str) -> bool: return bool(line.strip()) and not line.startswith(_INDENTED) and not _LIST_ITEM.match(line) -def _block_start(lines: list[str], i: int) -> bool: - """Whether a block may start at line ``i``: the first line, or after a blank line, a heading or an underline.""" +def _block_start(lines: list[str], i: int, fresh: int) -> bool: + """Whether a block may start at line ``i``. + + That is the first line, a line after a blank line, a heading, an underline, or a code + block (``fresh`` is the index where the last one ended). + """ + if i == 0 or i == fresh: + return True before = lines[i - 1] - return i == 0 or not before.strip() or bool(_HEADING.match(before) or _SETEXT.match(before)) + return not before.strip() or bool(_HEADING.match(before) or _SETEXT.match(before)) -def _indented_code_end(lines: list[str], i: int, in_list: bool) -> int: +def _indented_code_end(lines: list[str], i: int, in_list: bool, fresh: int) -> int: """The index one past the indented code block that starts at line ``i``, or 0 when none does. A block opens on a line indented four spaces or a tab that follows a blank line (or the @@ -214,30 +226,35 @@ def _indented_code_end(lines: list[str], i: int, in_list: bool) -> int: """ line = lines[i] if in_list or not line.strip() or not line.startswith(_INDENTED) \ - or not _block_start(lines, i): + or not _block_start(lines, i, fresh): return 0 end = i while end < len(lines): - row = lines[end] - if row.strip() and not row.startswith(_INDENTED): - break - if not row.strip() and not _indented_ahead(lines, end): + if lines[end].strip(): + if not lines[end].startswith(_INDENTED): + break + end += 1 + continue + ahead = end + 1 # a run of blank lines continues the block only before an indented line + while ahead < len(lines) and not lines[ahead].strip(): + ahead += 1 + if ahead == len(lines) or not lines[ahead].startswith(_INDENTED): break - end += 1 + end = ahead return end -def _setext(lines: list[str], i: int, front: int) -> tuple[int, int]: +def _setext(lines: list[str], i: int, front: int, fresh: int) -> tuple[int, int]: """``(level, end)`` when lines ``i`` up to ``end`` are a Setext heading, else ``(0, i)``. The text is one or more lines of a paragraph over an underline of ``=`` (level 1) or ``-`` (level 2). ``front`` is the index of the closing ``---`` of front matter, which underlines - nothing. + nothing. ``fresh`` is the index where the last code block ended. """ structural = (_HEADING, _FENCE, _TABLE_ROW, _LIST_ITEM) line = lines[i] if not line.strip() or line.startswith(_INDENTED) or _SETEXT.match(line) \ - or not _block_start(lines, i) or any(rule.match(line) for rule in structural): + or not _block_start(lines, i, fresh) or any(rule.match(line) for rule in structural): return 0, i for k in range(i + 1, len(lines)): row = lines[k] @@ -263,6 +280,7 @@ def segment(text: str) -> list[Span]: offset = 0 i = 0 in_list = False + fresh = 0 # the index where a code block last ended: a new block may start there front = _front_matter_end(lines) def emit(kind: str, chunk: str, start: int) -> None: @@ -287,11 +305,11 @@ def emit(kind: str, chunk: str, start: int) -> None: start = offset in_list = in_list and not _leaves_list(line) - code_end = _indented_code_end(lines, i, in_list) + code_end = _indented_code_end(lines, i, in_list, fresh) if code_end: block = lines[i:code_end] offset += sum(len(row) for row in block) - i = code_end + i = fresh = code_end emit("code", "".join(block), start) continue @@ -299,11 +317,11 @@ def emit(kind: str, chunk: str, start: int) -> None: end = _fence_end(lines, i) block = lines[i:end] offset += sum(len(row) for row in block) - i = end + i = fresh = end emit("code", "".join(block), start) continue - level, end = _setext(lines, i, front) + level, end = _setext(lines, i, front, fresh) if level: block = lines[i:end] del heading_path[level - 1:] @@ -331,15 +349,10 @@ def emit(kind: str, chunk: str, start: int) -> None: if _LIST_ITEM.match(line): # A list item continues over indented follow-on lines. - block = [line] - offset += len(line) - i += 1 - while i < len(lines) and lines[i].strip() and not _LIST_ITEM.match(lines[i]) \ - and not _HEADING.match(lines[i]) and not _FENCE.match(lines[i]) \ - and lines[i].startswith((" ", "\t")): - block.append(lines[i]) - offset += len(lines[i]) - i += 1 + end = _list_item_end(lines, i + 1) + block = lines[i:end] + offset += sum(len(row) for row in block) + i = end emit("list_item", "".join(block), start) in_list = True continue diff --git a/dokimi/scripts/growth_baseline.json b/dokimi/scripts/growth_baseline.json index c1d9effd34..ce6052d21c 100644 --- a/dokimi/scripts/growth_baseline.json +++ b/dokimi/scripts/growth_baseline.json @@ -47,7 +47,7 @@ "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": 15}, + "dokimi/novelty/spans.py::segment": {"complexity": 14}, "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_spans.py b/dokimi/tests/test_novelty_spans.py index 7318b1553b..22374ba1d5 100644 --- a/dokimi/tests/test_novelty_spans.py +++ b/dokimi/tests/test_novelty_spans.py @@ -164,7 +164,59 @@ 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 not segment("---\nname: s\n---\n\nHi there.\n")[0].kind == "heading" + 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_indented_code_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_code_end + + n = 2000 + lines = [_CountingLine(row) for row in [" a\n"] + ["\n"] * n + [" b\n"]] + _CountingLine.reads = 0 + assert _indented_code_end(lines, 0, False, 0) == 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(): From 95182a0b0d66d48f49331f5040d328cef6825ec7 Mon Sep 17 00:00:00 2001 From: vchamarthi <123653452+vchamarthi@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:37:33 -0600 Subject: [PATCH 3/8] fix(novelty): indented ATX headings, CRLF underlines, bare rules in spans - An ATX heading indented up to three spaces is a heading, so a bundled file that starts with ` # Setup` keeps its heading path. - A Setext underline may end in a carriage return, so CRLF text is segmented like LF text. - dangling_fence now finds Setext headings the way segment does instead of reading every underline-shaped line as a finished heading, so a bare `---` no longer lets the next file be swallowed into a code span. - An ATX heading needs a space or tab after the #s, not any whitespace, so an empty indented heading reads alike in segment and dangling_fence. Signed-off-by: vchamarthi <123653452+vchamarthi@users.noreply.github.com> --- ...261126_150000_novelty-walkthrough-spans.md | 2 +- dokimi/dokimi/novelty/spans.py | 19 ++++--- dokimi/tests/test_novelty_spans.py | 49 +++++++++++++++++++ 3 files changed, 63 insertions(+), 7 deletions(-) diff --git a/dokimi/changelog.d/20261126_150000_novelty-walkthrough-spans.md b/dokimi/changelog.d/20261126_150000_novelty-walkthrough-spans.md index a8475a39ab..2e75b012e5 100644 --- a/dokimi/changelog.d/20261126_150000_novelty-walkthrough-spans.md +++ b/dokimi/changelog.d/20261126_150000_novelty-walkthrough-spans.md @@ -4,6 +4,6 @@ (`Title` over `====` or `----`) is one heading span and a run of four-space or tab indented lines after a blank line, outside a list, is one code span, so `analyze` and `--estimate-only` no longer count their sentences as extra spans (and span ids shift for artifacts that use these - forms). The walkthrough now says that `analyze --max-usd` stopped in measurement leaves + forms; an ATX heading indented up to three spaces and a Setext underline with CRLF line endings count too). 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/dokimi/novelty/spans.py b/dokimi/dokimi/novelty/spans.py index 70140ba850..c528e6b246 100644 --- a/dokimi/dokimi/novelty/spans.py +++ b/dokimi/dokimi/novelty/spans.py @@ -42,10 +42,11 @@ # 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+(.*)$") +# Spaces or tabs only after the `#`s: a line ending (kept by `segment`, dropped by `dangling_fence`) must not count. +_HEADING = re.compile(r"^ {0,3}(#{1,6})[ \t]+(.*)$") _LIST_ITEM = re.compile(r"^\s*(?:[-*+]|\d+[.)])\s+") # A Setext underline: a run of `=` (level 1) or `-` (level 2) under a line of text. -_SETEXT = re.compile(r"^ {0,3}(=+|-+)[ \t]*$") +_SETEXT = re.compile(r"^ {0,3}(=+|-+)[ \t]*\r?$") _INDENTED = (" ", "\t") _TABLE_ROW = re.compile(r"^\s*\|.*\|\s*$") # Sentence split on terminal punctuation followed by whitespace + a capital/backtick. @@ -142,6 +143,7 @@ def dangling_fence(text: str) -> str | None: lines = text.splitlines() in_list = False fresh = 0 # the index where a code block last ended: a new block may start there + front = _front_matter_end(lines) i = 0 while i < len(lines): line = lines[i] @@ -160,6 +162,10 @@ def dangling_fence(text: str) -> str | None: if opened: marker = opened.group(1) continue + level, end = _setext(lines, i - 1, front, fresh) + if level: # a heading ends here, so a new block may start straight after it + i = fresh = end + continue if _LIST_ITEM.match(line): # its continuation lines belong to it, as in segment i = _list_item_end(lines, i) in_list = True @@ -209,13 +215,14 @@ def _leaves_list(line: str) -> bool: def _block_start(lines: list[str], i: int, fresh: int) -> bool: """Whether a block may start at line ``i``. - That is the first line, a line after a blank line, a heading, an underline, or a code - block (``fresh`` is the index where the last one ended). + That is the first line, a line after a blank line or an ATX heading, or the line where a + code block or a Setext heading ended (``fresh``). A bare ``---`` is not an underline here: + only :func:`_setext` says whether it closed a heading. """ if i == 0 or i == fresh: return True before = lines[i - 1] - return not before.strip() or bool(_HEADING.match(before) or _SETEXT.match(before)) + return not before.strip() or bool(_HEADING.match(before)) def _indented_code_end(lines: list[str], i: int, in_list: bool, fresh: int) -> int: @@ -327,7 +334,7 @@ def emit(kind: str, chunk: str, start: int) -> None: del heading_path[level - 1:] heading_path.append(" ".join(row.strip() for row in block[:-1])) offset += sum(len(row) for row in block) - i = end + i = fresh = end emit("heading", "".join(block), start) continue diff --git a/dokimi/tests/test_novelty_spans.py b/dokimi/tests/test_novelty_spans.py index 22374ba1d5..20931dd23b 100644 --- a/dokimi/tests/test_novelty_spans.py +++ b/dokimi/tests/test_novelty_spans.py @@ -323,3 +323,52 @@ def test_a_leading_rule_is_not_front_matter(): spans = segment("---\n\nTitle. More\n---\n\nBody.\n") assert [s.kind for s in spans] == ["sentence", "heading", "sentence"] assert spans[2].heading_path == ("Title. More",) + + +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_read_alike_by_segment_and_dangling_fence(): + """#974: ` #` plus a line ending is no heading in either, so both see the same fence.""" + from dokimi.novelty.bundle import BundleFile, _stitch + + source = " #\n ```\n example\n" + assert segment(source)[0].kind == "sentence" + assert dangling_fence(source) == "```" + spans = segment(_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 spans) + assert any(s.text == "Reference sentence." for s in spans) From 9e992b9ecae78ad3c5358e062186bad74acdf016 Mon Sep 17 00:00:00 2001 From: Alexander Rybkin Date: Sun, 29 Nov 2026 02:49:15 -0800 Subject: [PATCH 4/8] fix(novelty): an empty list item is a list item in segment and dangling_fence _LIST_ITEM ended in \s+, which matched the line ending segment keeps but dangling_fence drops. A lone `-` or `1.` opened a list for one and not the other, so _stitch left a fence open and swallowed the next file. Signed-off-by: Alexander Rybkin --- dokimi/dokimi/novelty/spans.py | 2 +- dokimi/tests/test_novelty_spans.py | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/dokimi/dokimi/novelty/spans.py b/dokimi/dokimi/novelty/spans.py index c528e6b246..01d602de02 100644 --- a/dokimi/dokimi/novelty/spans.py +++ b/dokimi/dokimi/novelty/spans.py @@ -44,7 +44,7 @@ _FENCE = re.compile(r"^\s*(`{3,}(?!.*`)|~{3,})") # Spaces or tabs only after the `#`s: a line ending (kept by `segment`, dropped by `dangling_fence`) must not count. _HEADING = re.compile(r"^ {0,3}(#{1,6})[ \t]+(.*)$") -_LIST_ITEM = re.compile(r"^\s*(?:[-*+]|\d+[.)])\s+") +_LIST_ITEM = re.compile(r"^\s*(?:[-*+]|\d+[.)])(?:[ \t]+|\r?$)") # A Setext underline: a run of `=` (level 1) or `-` (level 2) under a line of text. _SETEXT = re.compile(r"^ {0,3}(=+|-+)[ \t]*\r?$") _INDENTED = (" ", "\t") diff --git a/dokimi/tests/test_novelty_spans.py b/dokimi/tests/test_novelty_spans.py index 20931dd23b..084d84c369 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, @@ -372,3 +374,16 @@ def test_an_indented_empty_atx_heading_is_read_alike_by_segment_and_dangling_fen BundleFile("references/r.md", "reference", "Reference sentence.")])) 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) + + +@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) From bffac7d656eac6a9c11be8a497b179f75ff4c08b Mon Sep 17 00:00:00 2001 From: Alexander Rybkin Date: Sun, 29 Nov 2026 02:49:38 -0800 Subject: [PATCH 5/8] test(novelty): a structural line under a paragraph line ends the Setext lookahead Without the structural break in _setext, `Intro line` over a fence with a YAML `---` became a heading that swallowed half the fence; no test failed. Signed-off-by: Alexander Rybkin --- dokimi/tests/test_novelty_spans.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/dokimi/tests/test_novelty_spans.py b/dokimi/tests/test_novelty_spans.py index 084d84c369..41fcd9d054 100644 --- a/dokimi/tests/test_novelty_spans.py +++ b/dokimi/tests/test_novelty_spans.py @@ -387,3 +387,11 @@ def test_an_empty_list_item_is_read_alike_by_segment_and_dangling_fence(item): 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) From 1f5a73da44913b6cc092c550edd6c17f99c07dc7 Mon Sep 17 00:00:00 2001 From: Alexander Rybkin Date: Sun, 29 Nov 2026 02:50:11 -0800 Subject: [PATCH 6/8] fix(novelty): a blockquote or HTML comment over --- is no Setext heading `> rule` over `---` became a heading, so `trace prefilter` lost the rule and used it as the next claim's heading. CommonMark reads the block and a thematic break. The changelog fragment now names `trace prefilter`. Signed-off-by: Alexander Rybkin --- .../20261126_150000_novelty-walkthrough-spans.md | 2 +- dokimi/dokimi/novelty/spans.py | 4 +++- dokimi/tests/test_novelty_spans.py | 12 ++++++++++++ 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/dokimi/changelog.d/20261126_150000_novelty-walkthrough-spans.md b/dokimi/changelog.d/20261126_150000_novelty-walkthrough-spans.md index 2e75b012e5..c3e43791bd 100644 --- a/dokimi/changelog.d/20261126_150000_novelty-walkthrough-spans.md +++ b/dokimi/changelog.d/20261126_150000_novelty-walkthrough-spans.md @@ -4,6 +4,6 @@ (`Title` over `====` or `----`) is one heading span and a run of four-space or tab indented lines after a blank line, outside a list, is one code span, so `analyze` and `--estimate-only` no longer count their sentences as extra spans (and span ids shift for artifacts that use these - forms; an ATX heading indented up to three spaces and a Setext underline with CRLF line endings count too). The walkthrough now says that `analyze --max-usd` stopped in measurement leaves + forms; an ATX heading indented up to three spaces and a Setext underline with CRLF line endings count too). `trace prefilter` reads guidance with the same spans, so its claim ids shift the same way; a blockquote or HTML comment line over `---` stays its own block there and in `skill novelty`. 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/dokimi/novelty/spans.py b/dokimi/dokimi/novelty/spans.py index 01d602de02..893d03d95e 100644 --- a/dokimi/dokimi/novelty/spans.py +++ b/dokimi/dokimi/novelty/spans.py @@ -47,6 +47,8 @@ _LIST_ITEM = re.compile(r"^\s*(?:[-*+]|\d+[.)])(?:[ \t]+|\r?$)") # A Setext underline: a run of `=` (level 1) or `-` (level 2) under a line of text. _SETEXT = re.compile(r"^ {0,3}(=+|-+)[ \t]*\r?$") +# A blockquote or HTML comment over `---` is that block and a rule, never Setext text (CommonMark). +_QUOTE_OR_COMMENT = re.compile(r"^ {0,3}(?:>|\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")) From 9a769c72ac9ac2a1f8144440afd9fa1b7ff7f277 Mon Sep 17 00:00:00 2001 From: vchamarthi <123653452+vchamarthi@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:28:01 -0600 Subject: [PATCH 7/8] fix(novelty): dangling_fence reads text as segment does (#974) Main's segment (#1045) already makes Setext headings and indented code one span each. On top of it: - dangling_fence returns the fence segment leaves open, so a stitched bundle agrees with segment on indented backticks, list continuations, empty list items and CRLF. - indented code is read before a fence, so four-space backticks after a blank line are code. - indented code or a Setext heading may follow a closed fence or a heading directly; an ATX heading may be indented up to three spaces. - the growth baseline entry for segment is dropped. - a lone `-` under a paragraph line is a level-two Setext underline. Signed-off-by: vchamarthi <123653452+vchamarthi@users.noreply.github.com> --- dokimi/dokimi/novelty/spans.py | 120 +++++++----- dokimi/scripts/growth_baseline.json | 1 - dokimi/tests/test_novelty_spans.py | 286 +++++++++++++++++++++++++++- 3 files changed, 355 insertions(+), 52 deletions(-) diff --git a/dokimi/dokimi/novelty/spans.py b/dokimi/dokimi/novelty/spans.py index 1d31fdfb2f..1d42c979e5 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 2ccd7c396e..52e89aee51 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_spans.py b/dokimi/tests/test_novelty_spans.py index 152ba640db..8e38fe6e37 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,285 @@ 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_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",) From 0af133df4df0d6bb7ce275ddc6d276f18e77f623 Mon Sep 17 00:00:00 2001 From: vchamarthi Date: Mon, 30 Nov 2026 22:52:10 +0000 Subject: [PATCH 8/8] fix(novelty): _stitch reads a file's open fence under its heading (#974) A reference whose front matter has a blank line was scanned alone, so its fence status differed from the stitched document and the appended backticks opened a fence over the next file. Scan the heading and body together, as they are stitched. Signed-off-by: vchamarthi --- dokimi/dokimi/novelty/bundle.py | 3 ++- dokimi/tests/test_novelty_spans.py | 13 +++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/dokimi/dokimi/novelty/bundle.py b/dokimi/dokimi/novelty/bundle.py index 7de8e7b13f..714d801d45 100644 --- a/dokimi/dokimi/novelty/bundle.py +++ b/dokimi/dokimi/novelty/bundle.py @@ -615,7 +615,8 @@ def _stitch(files: list[BundleFile]) -> str: header = "" if index == 0 else f"\n\n{BUNDLE_HEADER_PREFIX}{item.role}: {item.path}\n\n" # 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() - marker = dangling_fence(body) + # 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/tests/test_novelty_spans.py b/dokimi/tests/test_novelty_spans.py index 8e38fe6e37..65ac5c6831 100644 --- a/dokimi/tests/test_novelty_spans.py +++ b/dokimi/tests/test_novelty_spans.py @@ -569,6 +569,19 @@ def test_dangling_fence_agrees_with_segment_on_a_backtick_line_in_indented_code( 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")