Skip to content

Commit 11a3b05

Browse files
cdeustclaude
andcommitted
fix(wiki): one reading of a draft section for every consumer (#589)
The Markdown renderer skipped a section with no heading while handlers/wiki_compile.py mirrored it into wiki.pages.sections under an empty key, so a file and its row described the same page differently. core/draft_curator.py called .strip() on whatever the section held, raising AttributeError on a heading that was not text, and on a Section object whose heading was empty. mcp_server/shared/wiki_sections.py states the shape once (is_text, heading_of, body_of, titled_sections) and the renderer, the mirror, the curator's required-section lookup and wiki_refine_draft's validation all read a section through it (ADR-1071). wiki_refine_draft also refuses two sections carrying the same heading, which the mirror's mapping silently deduped. Three of the new cases fail on the previous code, one with the AttributeError. Full suite: 8716 passed, 8 skipped. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Cz7A6goxVzfKL9NT7k4zDH
1 parent 3138ec6 commit 11a3b05

14 files changed

Lines changed: 439 additions & 29 deletions

‎CHANGELOG.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,14 @@ adheres to [Semantic Versioning](https://semver.org/).
5151
client-visible schema comes from the registered wrapper's signature. Both
5252
fields are now validated as non-blank text, and a number for either returns a
5353
validation error instead of raising `AttributeError` (ADR-1070).
54+
- **The wiki.pages mirror holds what the page holds (#589).** The Markdown
55+
renderer dropped a section with no heading while `handlers/wiki_compile.py`
56+
mirrored it into `wiki.pages.sections` under an empty key, so a file and its
57+
row described the same page differently, and `core/draft_curator.py` raised
58+
`AttributeError` on a heading that was not text. The four readings of a
59+
section now come from one place, `mcp_server/shared/wiki_sections.py`, and
60+
`wiki_refine_draft` also refuses two sections carrying the same heading,
61+
which the mirror's mapping silently deduped (ADR-1071).
5462
- **Refining a wiki draft no longer raises its confidence (#578).**
5563
`handler_refine` (`mcp_server/handlers/wiki_refine.py`) wrote a fixed 0.85
5664
into every refined draft and its `refined_llm` memo, which put the draft past
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<!-- Generated by Cortex wiki_reindex from wiki/adr/cortex/1071-one-reading-of-a-draft-section-for-every-consumer.md; ADR-1071. Read-only mirror: edit the canonical wiki page. -->
2+
3+
---
4+
created: 2026-09-16T07:39:09Z
5+
kind: adr
6+
number: 1071
7+
status: accepted
8+
tags: [wiki, curation, compile, shared, issue-589]
9+
title: One reading of a draft section for every consumer
10+
---
11+
# ADR-1071: One reading of a draft section for every consumer
12+
13+
## Status
14+
15+
accepted
16+
17+
## Context
18+
19+
A wiki draft's sections are read in four places, and each spelled out the shape for itself, with different answers (issue #589):
20+
21+
- `core/draft_compiler.py` skipped a section whose heading was falsy, so the published Markdown never carried an untitled section.
22+
- `handlers/wiki_compile.py` built the `wiki.pages` mirror as a `{heading: body}` comprehension with no guard, so the same section landed in the row under an empty key. The file and its mirror disagreed about the same page. The review of PR #588 demonstrated it: a draft holding `sections=[{"heading": "", "body": "orphan prose"}]` compiled to a `.md` without the section and to `wiki.pages.sections == {"": "orphan prose"}`.
23+
- `core/draft_curator.py::_missing_required_sections` called `.strip()` on whatever the section held, so a heading that was not text raised `AttributeError` inside `evaluate_draft`, and `getattr(s, "heading", None) or s.get("heading", "")` raised on a `Section` object whose heading was empty.
24+
- `handlers/wiki_refine.py` had its own `_is_text` since ADR-1070, which is the only one of the four that was right.
25+
26+
A section arrives either as a dict, from an MCP client through `wiki_refine_draft`, or as a `Section` object from the template synthesizer, and ADR-1070 only closed the client entry point. A draft written before it, or by `wiki_synthesize`, still reaches the other three.
27+
28+
Two sections submitted with the same heading were also silently deduped by the mirror's mapping: the second body replaced the first with no error.
29+
30+
## Decision
31+
32+
`mcp_server/shared/wiki_sections.py` states the shape once: `is_text` for a non-blank string, `heading_of` returning the stripped heading or None, `body_of` returning the body or an empty string, and `titled_sections` returning the ordered `(heading, body)` pairs a page can carry. Being in `shared/`, it is reachable from core, handlers and infrastructure alike.
33+
34+
The Markdown renderer, the `wiki.pages` mirror and the curator's required-section lookup all read a draft through `titled_sections`, so the file, the row and the curation verdict describe the same page. `wiki_refine_draft` keeps refusing a malformed section at the entry point, and now also refuses two sections that carry the same heading, since the mirror cannot hold both.
35+
36+
## Consequences
37+
38+
Easier: a page row can no longer carry prose under an empty key, and the curator reports a malformed section as a missing required one instead of raising.
39+
40+
`tests_py/shared/test_wiki_sections.py` covers the four functions over dicts, `Section` objects, missing fields and non-text values. `tests_py/handlers/test_wiki_compile_sections_mirror.py` compiles a draft holding a blank heading, a missing heading and a numeric heading, and asserts the mirror holds only the titled section while the published Markdown omits the orphan prose. `tests_py/core/test_draft_curator_sections.py` drives four malformed shapes through `evaluate_draft`. `test_duplicate_headings_are_refused` covers the refine entry point. Three of those fail on the previous code, one of them with the `AttributeError`.
41+
42+
Harder: a consumer that wanted the raw sections, with their unusable entries, has to read the draft column itself. None does.
43+
44+
Unchanged: what the synthesizer writes, and what `wiki_curate` decides for a well-formed draft.

‎docs/module-inventory.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ not exist." The registered tools are listed in `docs/mcp-tools.md`.
5757
- `wiki_index.py` — `build_index` (INDEX.md generation). Moved from `core/` alongside `wiki_frontmatter.py`
5858
- `wiki_pages.py` — Composed public entry point re-exporting `wiki_frontmatter`/`wiki_page_builders`/`wiki_index`. Moved from `core/` alongside its three collaborators
5959
- `wiki_layout.py` — `PAGE_KINDS`, `slugify`, page-path helpers. Moved from `core/`: `re`/`pathlib.PurePosixPath` only (no filesystem I/O — `PurePosixPath` is pure string manipulation)
60+
- `wiki_sections.py` — One reading of a draft's sections for every consumer (`is_text`, `heading_of`, `body_of`, `titled_sections`): the Markdown renderer, the `wiki.pages` mirror and the curator all read a section through it, so a file and its row describe the same page (ADR-1071)
6061
- `wiki_readme.py` — `build_plain_readme` (non-technical top-level README generation). Moved from `core/` alongside `wiki_layout.py`
6162
- `wiki_frontmatter_validation.py` — `normalize_frontmatter`, the write-time choke point `infrastructure/wiki_store.py::write_page` runs on every full-page write (issue #107/#110). Moved from `core/` alongside `wiki_pages.py`
6263
- `wiki_schema_loader.py` — Self-hosting wiki schema data model (`KindDefinition`/`ClassifierRule`/`ViewDefinition`/`TriggerDefinition`/`WikiRegistry`) + pure `str -> dataclass` parsers; the adapter (`infrastructure/wiki_schema_reader.py`) walks the filesystem and feeds file content through these (issue #126 port-and-adapter split). Moved from `core/` (issue: same infra→core violation as the rest of this cluster) — `re`/`dataclasses`/`pathlib.Path.stem` only, zero I/O of its own

‎mcp_server/core/draft_compiler.py‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from datetime import datetime, timezone
99

1010
from mcp_server.shared.wiki_layout import slugify
11+
from mcp_server.shared.wiki_sections import titled_sections
1112

1213
_FRONTMATTER_KEYS_ORDER = (
1314
"title",
@@ -165,12 +166,8 @@ def compile_draft(
165166
body_parts.append(f"# {title}\n")
166167
if lead:
167168
body_parts.append(f"{lead}\n")
168-
for s in sections:
169-
heading = s.get("heading") if isinstance(s, dict) else getattr(s, "heading", "")
170-
body = s.get("body") if isinstance(s, dict) else getattr(s, "body", "")
171-
if not heading:
172-
continue
173-
body_parts.append(_section_md(str(heading), str(body or "")))
169+
for heading, body in titled_sections(sections):
170+
body_parts.append(_section_md(heading, body))
174171

175172
if backlinks:
176173
body_parts.append("## See also\n")

‎mcp_server/core/draft_curator.py‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from typing import Literal
1010

1111
from mcp_server.shared.wiki_schema_loader import KindDefinition
12+
from mcp_server.shared.wiki_sections import titled_sections
1213

1314
CurationVerdict = Literal["approved", "rejected", "hold"]
1415

@@ -58,12 +59,8 @@ def _section_is_filled(body: str) -> bool:
5859

5960
def _missing_required_sections(sections: list, required: list[str]) -> list[str]:
6061
"""Return the subset of required sections that are missing or empty."""
61-
by_heading: dict[str, str] = {}
62-
for s in sections:
63-
# accept either Pydantic Section or dict
64-
heading = getattr(s, "heading", None) or s.get("heading", "")
65-
body = getattr(s, "body", None) or s.get("body", "")
66-
by_heading[heading.strip()] = body
62+
# Section or dict, either field possibly absent or not text (ADR-1071)
63+
by_heading: dict[str, str] = dict(titled_sections(sections))
6764
missing: list[str] = []
6865
for h in required:
6966
body = by_heading.get(h)

‎mcp_server/handlers/wiki_compile.py‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
)
3737
from mcp_server.infrastructure.wiki_store import write_page
3838
from mcp_server.shared.wiki_source_paths import extract_document_paths
39+
from mcp_server.shared.wiki_sections import titled_sections
3940

4041

4142
schema = {
@@ -152,12 +153,9 @@ def _publish_one(conn, draft: dict, *, dry_run: bool) -> dict:
152153
"status": frontmatter.get("status", "seedling"),
153154
"lifecycle_state": frontmatter.get("lifecycle_state", "active"),
154155
"lead": (draft.get("lead") or "").strip(),
155-
"sections": {
156-
(s.get("heading") if isinstance(s, dict) else getattr(s, "heading", "")): (
157-
s.get("body") if isinstance(s, dict) else getattr(s, "body", "")
158-
)
159-
for s in (draft.get("sections") or [])
160-
},
156+
# The mirror holds what the page holds: a section with no usable
157+
# heading is not on the page (ADR-1071).
158+
"sections": dict(titled_sections(draft.get("sections"))),
161159
"body": markdown,
162160
"body_hash": body_hash(markdown),
163161
"documents": documents,

‎mcp_server/handlers/wiki_refine.py‎

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,11 @@
1919
from typing import Any
2020

2121
from mcp_server.handlers._tool_meta import NON_IDEMPOTENT_WRITE, READ_ONLY
22+
from mcp_server.shared.wiki_sections import (
23+
body_of,
24+
heading_of,
25+
titled_sections,
26+
)
2227
from mcp_server.infrastructure.wiki_schema_reader import load_registry
2328
from mcp_server.infrastructure.config import WIKI_ROOT
2429
from mcp_server.infrastructure.memory_config import get_memory_settings
@@ -285,11 +290,6 @@ def _content_refusal(args: dict[str, Any]) -> str | None:
285290
return None
286291

287292

288-
def _is_text(value: Any) -> bool:
289-
"""Non-blank text. A section's heading and body are both of that shape."""
290-
return isinstance(value, str) and bool(value.strip())
291-
292-
293293
def _validate_against_contract(
294294
sections: list[dict], required_sections: list[str]
295295
) -> list[str]:
@@ -300,17 +300,21 @@ def _validate_against_contract(
300300
registered wrapper's signature, so the check belongs here (ADR-1070).
301301
"""
302302
errors: list[str] = []
303-
headings = {s["heading"].strip() for s in sections if _is_text(s.get("heading"))}
303+
headings = {heading for heading, _ in titled_sections(sections)}
304304
for req in required_sections:
305305
if req not in headings:
306306
errors.append(f"required section missing: {req!r}")
307+
seen: set[str] = set()
307308
for index, section in enumerate(sections):
308-
heading = section.get("heading")
309-
if not _is_text(heading):
309+
heading = heading_of(section)
310+
if heading is None:
310311
errors.append(f"section {index}: heading must be non-blank text")
311-
if not _is_text(section.get("body")):
312-
name = heading if _is_text(heading) else index
313-
errors.append(f"section {name!r} has empty body")
312+
elif heading in seen:
313+
errors.append(f"duplicate section heading: {heading!r}")
314+
else:
315+
seen.add(heading)
316+
if not body_of(section):
317+
errors.append(f"section {heading if heading else index!r} has empty body")
314318
return errors
315319

316320

‎mcp_server/shared/wiki_sections.py‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
"""One reading of a wiki draft's sections: a heading and a body, both text.
2+
3+
A section reaches the pipeline either as a dict, from an MCP client through
4+
`wiki_refine_draft`, or as a `Section` object from the template synthesizer,
5+
and either field can be absent or hold something that is not text. Every
6+
consumer used to spell that out for itself, and disagreed: the Markdown
7+
renderer skipped a section with no heading while the `wiki.pages` mirror kept
8+
it under an empty key, and the curator called `.strip()` on whatever it found.
9+
10+
source: ADR-1071"""
11+
12+
from __future__ import annotations
13+
14+
from typing import Any
15+
16+
17+
def is_text(value: Any) -> bool:
18+
"""Non-blank text. The shape a heading and a body must have."""
19+
return isinstance(value, str) and bool(value.strip())
20+
21+
22+
def _field(section: Any, name: str) -> Any:
23+
if isinstance(section, dict):
24+
return section.get(name)
25+
return getattr(section, name, None)
26+
27+
28+
def heading_of(section: Any) -> str | None:
29+
"""The section's heading, stripped, or None when it carries no usable one."""
30+
heading = _field(section, "heading")
31+
return heading.strip() if is_text(heading) else None
32+
33+
34+
def body_of(section: Any) -> str:
35+
"""The section's body, or an empty string when it carries no text."""
36+
body = _field(section, "body")
37+
return body if is_text(body) else ""
38+
39+
40+
def titled_sections(sections: Any) -> list[tuple[str, str]]:
41+
"""The (heading, body) pairs a page can carry, in order.
42+
43+
A section with no usable heading has nowhere to go on the page and is
44+
dropped, which is what the Markdown renderer has always done.
45+
"""
46+
pairs: list[tuple[str, str]] = []
47+
for section in sections or []:
48+
heading = heading_of(section)
49+
if heading is not None:
50+
pairs.append((heading, body_of(section)))
51+
return pairs
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
"""The curator reads a draft's sections without assuming their shape (#589).
2+
3+
`_missing_required_sections` called `.strip()` on whatever a section held, so
4+
a heading that was not text raised `AttributeError` inside `evaluate_draft`,
5+
and a `Section` object with an empty heading raised on the `.get` fallback.
6+
7+
source: ADR-1071
8+
"""
9+
10+
from __future__ import annotations
11+
12+
import pytest
13+
14+
from mcp_server.core.draft_curator import evaluate_draft
15+
from mcp_server.shared.wiki_schema_loader import KindDefinition
16+
17+
FILLED = "Prose long enough to count as a filled section."
18+
19+
20+
def _kind(required: tuple[str, ...]) -> KindDefinition:
21+
return KindDefinition(
22+
name="adr",
23+
display_name="ADR",
24+
dir_name="adr",
25+
required_sections=list(required),
26+
)
27+
28+
29+
def _draft(sections: list) -> dict:
30+
return {
31+
"confidence": 0.9,
32+
"title": "A settled decision",
33+
"lead": "What was decided and why.",
34+
"sections": sections,
35+
}
36+
37+
38+
@pytest.mark.parametrize(
39+
"section",
40+
[
41+
{"heading": 3, "body": FILLED},
42+
{"body": FILLED},
43+
{"heading": " ", "body": FILLED},
44+
{},
45+
],
46+
ids=["heading-not-text", "no-heading", "blank-heading", "empty-section"],
47+
)
48+
def test_a_malformed_section_is_reported_not_raised(section) -> None:
49+
decision = evaluate_draft(_draft([section]), _kind(("Context",)))
50+
51+
assert decision.verdict != "approved"
52+
assert any("missing required sections" in reason for reason in decision.reasons)
53+
54+
55+
def test_a_well_formed_section_still_satisfies_its_requirement() -> None:
56+
decision = evaluate_draft(
57+
_draft([{"heading": "Context", "body": FILLED}]), _kind(("Context",))
58+
)
59+
60+
assert decision.verdict == "approved"
61+
assert decision.reasons == ()

0 commit comments

Comments
 (0)