Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions dokimi/changelog.d/20261126_150000_novelty-walkthrough-spans.md
Original file line number Diff line number Diff line change
@@ -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`.
20 changes: 13 additions & 7 deletions dokimi/docs/skill-novelty-walkthrough.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ follows the artifact's length and the models. Pass `--max-usd <n>` 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.

Expand All @@ -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 `<stem>.partial.json` holds anything
other than a partial result, the new one goes to `<stem>.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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
6 changes: 4 additions & 2 deletions dokimi/dokimi/novelty/bundle.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Comment thread
vchamarthi marked this conversation as resolved.
Resolved
# 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"
Expand Down
120 changes: 70 additions & 50 deletions dokimi/dokimi/novelty/spans.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]]] = [
Expand All @@ -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}<!--")
_QUOTE = re.compile(r"^ {0,3}>")
Expand Down Expand Up @@ -150,20 +152,14 @@
def dangling_fence(text: str) -> str | None:
"""The marker of a code fence ``text`` opens and never closes, or ``None``.

Same rule as :func:`segment`: a fence closes only on a line holding nothing but a run
of the marker's character at least as long as the marker, so ```` ``` ```` inside a
``~~~`` block or a ```` ```` ```` block, or ```` ```python ```` in any block, is
content. Anything that concatenates texts (the bundle renderer) must use this, not
fence-line parity, or the two disagree and the next text is swallowed into one code span.
It reads ``text`` the way :func:`segment` does, so a fence line inside indented code, a
comment or a list item is content, and a fence closes only on a line holding nothing but
a run of the marker's character at least as long as the marker (```` ``` ```` inside a
``~~~`` block, or ```` ```python ```` in any block, is content). Anything that
concatenates texts (the bundle renderer) must use this, not 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
return marker
return _scan(text)[1]
Comment thread
vchamarthi marked this conversation as resolved.
Resolved


def _frontmatter_end(lines: list[str]) -> int:
Expand Down Expand Up @@ -309,19 +305,33 @@
emit(item_kind, text, start + at, whole)


def _scaffold(lines: list[str], i: int, spans: list[Span], in_list: bool) -> tuple[str, int, int] | None:
def _opens_code(lines: list[str], i: int, in_list: bool, fresh: int) -> bool:
"""Whether line ``i`` opens indented code: indented, outside a list, after a blank line or where a block ended."""
return bool(_INDENTED.match(lines[i])) and not in_list and (i in (0, fresh) or not lines[i - 1].strip())


def _fence_block(lines: list[str], i: int, fence: str) -> tuple[int, bool]:
"""``(end, closed)``: the index after the fenced block opened by ``fence`` on line ``i``, and whether it closed."""
for n in range(i + 1, len(lines)):
if _closes(lines[n], fence):
return n + 1, True
return len(lines), False


def _scaffold(lines: list[str], i: int, spans: list[Span], in_list: bool, fresh: int = -1) -> tuple[str, int, int] | None:

Check warning on line 321 in dokimi/dokimi/novelty/spans.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: bump-int `1` -> `2`
"""The Markdown block that starts at line ``i`` and is not prose, as ``(kind, end line, heading level)``, or ``None``.

A ``#`` heading, an indented code block (after a blank line, and not the continuation of a list item), an
HTML comment that closes, or a Setext heading. A comment closing mid-line splits that line (in place) in two.
``in_list``: the line is inside a list item. A line directly under a list item continues it and underlines
into no heading.
into no heading. ``fresh``: the line where the last fence, heading or code block ended, which may open a block
without a blank line before it.
"""
line = lines[i]
atx = _HEADING.match(line)
if atx:
return "heading", i + 1, len(atx.group(1))
if _INDENTED.match(line) and (i == 0 or not lines[i - 1].strip()) and not in_list:
if _opens_code(lines, i, in_list, fresh):
return "code", _block_end(lines, i, _INDENTED.match), 0
if _COMMENT_OPEN.match(line):
end = _comment_end(lines, i)
Expand All @@ -340,6 +350,32 @@
Table rows and list items are one span each, a Setext heading (a line underlined by
``===`` or ``---``) is a ``heading``, and prose paragraphs are split into sentences.
"""
return _scan(text)[0]


def _emit_span(spans: list[Span], heading_path: list[str], kind: str, chunk: str, start: int,
read: str | None = None) -> None:
"""Append the span of ``chunk`` (trimmed, offsets exact) to ``spans``; ``read`` is the text its rules are read from."""
stripped = chunk.strip()
if not stripped:
return
begin = start + len(chunk) - len(chunk.lstrip())
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, " ")),

Check warning on line 371 in dokimi/dokimi/novelty/spans.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: take-branch `() if kind == "comment" else protection_tags(_blank_comments(read or stripped, " "))` -> `(protection_tags(_blank_comments(read or stripped, " ")))`
))


def _scan(text: str) -> tuple[list[Span], str | None]:
""":func:`segment`'s spans and the marker of the fence left open at the end (see :func:`dangling_fence`)."""
dangling: str | None = None
fresh = -1 # the line where the last fence, heading or code block ended

Check warning on line 378 in dokimi/dokimi/novelty/spans.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: bump-int `1` -> `2`
spans: list[Span] = []
heading_path: list[str] = []
lines = text.splitlines(keepends=True)
Expand All @@ -348,42 +384,24 @@
in_list = False # inside a list item: indented lines are its content until a line that is not indented
after_comment = -1 # the line holding the text that followed a closing ``-->``: 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]
start = offset

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"))

Check warning on line 398 in dokimi/dokimi/novelty/spans.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: drop-element `(" ", "\t")` -> `("\t",)`

Check warning on line 398 in dokimi/dokimi/novelty/spans.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: drop-element `(" ", "\t")` -> `(" ",)`

Check warning on line 398 in dokimi/dokimi/novelty/spans.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: swap-boolop `in_list and line.startswith((" ", "\t"))` -> `in_list or line.startswith((' ', '\t'))`

Check warning on line 398 in dokimi/dokimi/novelty/spans.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: drop-clause `in_list and line.startswith((" ", "\t"))` -> `(line.startswith((" ", "\t")))`

Check warning on line 398 in dokimi/dokimi/novelty/spans.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: drop-clause `in_list and line.startswith((" ", "\t"))` -> `(in_list)`
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

Expand All @@ -394,13 +412,15 @@

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
Expand Down Expand Up @@ -442,7 +462,7 @@
# 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:
Expand Down
1 change: 0 additions & 1 deletion dokimi/scripts/growth_baseline.json
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand Down
38 changes: 38 additions & 0 deletions dokimi/tests/test_novelty_journey.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Loading
Loading