Skip to content
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
cb5b4a7
test: pin rich Markdown preview routing
stone16 Aug 1, 2026
bce91d8
feat: hand v3-only inline Markdown to scan
stone16 Aug 1, 2026
3a1fd98
docs: extend rich Markdown console handoff
stone16 Aug 1, 2026
cfa818b
refactor: centralize rich Markdown recognition
stone16 Aug 1, 2026
daadf3d
test: reject mixed malformed rich Markdown
stone16 Aug 1, 2026
6dc4047
fix: keep malformed rich previews generic
stone16 Aug 1, 2026
0359a9a
test: reject malformed link handoffs
stone16 Aug 1, 2026
da1605c
fix: validate rich inline handoff grammar
stone16 Aug 1, 2026
f17d7c8
test: reject malformed structured handoffs
stone16 Aug 1, 2026
2f4b73a
fix: inspect rich inline structural payloads
stone16 Aug 1, 2026
2544dbb
test: reject malformed fenced handoffs
stone16 Aug 1, 2026
211e1a6
fix: validate rich fenced handoff shape
stone16 Aug 1, 2026
9c54a23
test: cover structural rich inline handoffs
stone16 Aug 1, 2026
41c6c9d
fix: recognize rich rule structure
stone16 Aug 1, 2026
bc49e0d
test: reject malformed angle handoffs
stone16 Aug 1, 2026
e2a5038
fix: validate rich angle handoff shape
stone16 Aug 1, 2026
332cc79
test: preserve accepted angle handoff
stone16 Aug 1, 2026
2834955
fix: preserve rich angle literal precedence
stone16 Aug 1, 2026
d0d4f40
test: pin honest rich Markdown boundaries
stone16 Aug 1, 2026
796c1e8
fix: keep rich handoffs honest
stone16 Aug 1, 2026
6e9af65
docs: qualify rich handoff contract
stone16 Aug 1, 2026
50ae822
fix: reject indented fence handoffs
stone16 Aug 1, 2026
3f05e80
fix: align rich block handoff shape
stone16 Aug 1, 2026
7a02780
fix: bound rich HTML handoff blocks
stone16 Aug 1, 2026
365517a
fix: reject control-bearing rich handoffs
stone16 Aug 1, 2026
0bee808
fix: bound rich handoff token shapes
stone16 Aug 1, 2026
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
2 changes: 1 addition & 1 deletion STATUS.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ content. This activates no pi consumer, MCP Adapter, `Continue`, dogfood

| ADR | Activates |
|---|---|
| [0090](./docs/decisions/0090-admit-a-co-resident-local-evidence-console.md), [0093](./docs/decisions/0093-activate-leased-rich-markdown-and-revision-link-graph.md) | Explicitly authenticated server-rendered loopback UI, private File citation reopening, and separately Control-authorized source/import/Article jobs through schema-hidden typed HTTP carriers while OpenAPI v0 remains frozen; link-bearing imports receive a content-free handoff to the activated File scan and exact leased worker path |
| [0090](./docs/decisions/0090-admit-a-co-resident-local-evidence-console.md), [0093](./docs/decisions/0093-activate-leased-rich-markdown-and-revision-link-graph.md) | Explicitly authenticated server-rendered loopback UI, private File citation reopening, and separately Control-authorized source/import/Article jobs through schema-hidden typed HTTP carriers while OpenAPI v0 remains frozen; imports containing accepted rich links or v3-only emphasis, inline code, and strikethrough receive a content-free handoff to the activated File scan and exact leased worker path |

Feedback persists through the current Runtime identity and exact ContextRun
binding, with no Control or release-publication authority. Numeric Hit Test scores
Expand Down
39 changes: 28 additions & 11 deletions adapters/http/ui_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
MarkdownCompilerConfig,
ParsedDocument,
UnsupportedConstruct,
contains_rich_markdown_link,
contains_only_accepted_rich_markdown_inline,
)

_PREVIEW_TTL: Final = timedelta(minutes=10)
Expand All @@ -65,15 +65,24 @@
_MAX_SIGNED_BIGINT: Final = (1 << 63) - 1


def _contains_rich_markdown_link(source: bytes) -> bool:
def _decode_rich_markdown(source: bytes) -> str | None:
try:
decoded = source.removeprefix(b"\xef\xbb\xbf").decode(
return source.removeprefix(b"\xef\xbb\xbf").decode(
"utf-8",
errors="strict",
)
except UnicodeDecodeError:
return None


def _contains_only_accepted_rich_markdown_inline(
source: bytes,
construct: UnsupportedConstruct,
) -> bool:
decoded = _decode_rich_markdown(source)
if decoded is None:
return False
return contains_rich_markdown_link(decoded)
return contains_only_accepted_rich_markdown_inline(decoded, construct)


class UiApiUnavailable(RuntimeError):
Expand Down Expand Up @@ -806,14 +815,22 @@ def preview_import(
)
except (LookupError, RuntimeError, TypeError, ValueError):
raise UiApiUnavailable from None
requires_scan_handoff = (
(
type(outcome) is CompilationFailure
and outcome.code is CompilationFailureCode.UNSUPPORTED_CONSTRUCT
and outcome.construct is UnsupportedConstruct.LINK_OR_IMAGE
)
or _contains_rich_markdown_link(raw)
requires_scan_handoff = _contains_only_accepted_rich_markdown_inline(
raw,
UnsupportedConstruct.LINK_OR_IMAGE,
)
if (
type(outcome) is CompilationFailure
and outcome.code is CompilationFailureCode.UNSUPPORTED_CONSTRUCT
and outcome.construct is not None
):
requires_scan_handoff = (
requires_scan_handoff
or _contains_only_accepted_rich_markdown_inline(
raw,
outcome.construct,
)
)
if requires_scan_handoff:
source_arguments = (
"--organization-id "
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
name: adr-0093-activate-leased-rich-markdown-and-revision-link-graph
version: "1.0.1"
version: "1.0.2"
description: >
Activate rich Markdown v3 behind the exact File-import WorkerLease, persist
immutable content-free Revision link edges, and admit one authorized graph
Expand Down Expand Up @@ -43,13 +43,15 @@ ADR-0075 requires.
are not reinterpreted or backfilled. The co-resident local evidence console's
exact preview flow remains pinned to v1 because it has no durable import job
or WorkerLease redemption authority with which to select the v3 child. Issue
#203 ships the compatibility resolution: when v1's closed refusal is exactly
`LINK_OR_IMAGE`, or the exact source contains any accepted rich link syntax
not classified as such by v1, the console returns a content-free actionable
handoff to the existing source `scan` plus independent worker-dispatch path;
every other compilation refusal remains generically unavailable. The worker
honors a redeemed, exact v1 preview binding only for the console's successful
v1 preview/confirm flow; all scan-scheduled imports use active v3.
#203 and #207 ship the compatibility resolution: when v1's closed refusal is
exactly `LINK_OR_IMAGE`, `EMPHASIS`, `INLINE_CODE`, or `STRIKETHROUGH` and the
exact source matches that accepted v3 inline syntax, or when the source
contains accepted rich link syntax not classified as such by v1, the console
returns a content-free actionable handoff to the existing source `scan` plus
independent worker-dispatch path. Malformed syntax and every other compilation
refusal remain generically unavailable. The worker honors a redeemed, exact
v1 preview binding only for the console's successful v1 preview/confirm flow;
all scan-scheduled imports use active v3.
2. A File import redeems and durably verifies its exact WorkerLease before
selecting the rich compiler subprocess. The child is a pure transform that
receives source bytes, the closed configuration version, and token ceiling
Expand Down Expand Up @@ -139,8 +141,9 @@ an operating-system sandbox.

## Consequences

- Rich link-bearing File notes can now publish without changing v1/v2 bytes or
historical Revision meaning.
- File notes containing accepted rich links or v3-only emphasis, inline code,
and strikethrough can now publish without changing v1/v2 bytes or historical
Revision meaning.
- Outgoing links and backlinks are reproducible from immutable v3 Revision
lineage, but the graph itself grants no access and exposes no content.
- A denied neighbour is indistinguishable from an absent or irrelevant
Expand Down
4 changes: 4 additions & 0 deletions engine/supply/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@
StructuralPath,
UnsupportedConstruct,
canonicalize_parsed_document,
contains_accepted_rich_markdown_construct,
contains_only_accepted_rich_markdown_inline,
contains_rich_markdown_link,
deserialize_parsed_document,
)
Expand Down Expand Up @@ -175,6 +177,8 @@
"WorkerLeaseToken",
"generate_worker_lease_nonce",
"canonicalize_parsed_document",
"contains_accepted_rich_markdown_construct",
"contains_only_accepted_rich_markdown_inline",
"contains_rich_markdown_link",
"deserialize_parsed_document",
"worker_lease_digest",
Expand Down
145 changes: 111 additions & 34 deletions engine/supply/markdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -585,21 +585,43 @@ class UnsupportedConstruct(StrEnum):
r"th|td|p|ul|ol|li)\b[^>]*>",
re.IGNORECASE,
)
_ACCEPTED_RICH_MARKDOWN_CONSTRUCT_PATTERNS: Final = {
UnsupportedConstruct.EMPHASIS: (_EMPHASIS_PATTERN,),
UnsupportedConstruct.INLINE_CODE: (_RICH_INLINE_CODE_PATTERN,),
UnsupportedConstruct.LINK_OR_IMAGE: (
_RICH_WIKILINK_PATTERN,
_RICH_AUTOLINK_PATTERN,
_RICH_INLINE_LINK_PATTERN,
_RICH_REFERENCE_LINK_PATTERN,
),
UnsupportedConstruct.STRIKETHROUGH: (_RICH_STRIKETHROUGH_PATTERN,),
}


def contains_accepted_rich_markdown_construct(
source: str,
construct: UnsupportedConstruct,
) -> bool:
"""Return whether exact text contains the named accepted rich syntax."""

if type(source) is not str:
raise TypeError("rich Markdown construct detection requires exact text")
if type(construct) is not UnsupportedConstruct:
raise TypeError("rich Markdown construct detection requires a closed construct")
return any(
pattern.search(source) is not None
for pattern in _ACCEPTED_RICH_MARKDOWN_CONSTRUCT_PATTERNS.get(construct, ())
)


def contains_rich_markdown_link(source: str) -> bool:
"""Return whether exact UTF-8 text contains syntax accepted as a rich link."""

if type(source) is not str:
raise TypeError("rich Markdown link detection requires exact text")
return any(
pattern.search(source) is not None
for pattern in (
_RICH_WIKILINK_PATTERN,
_RICH_AUTOLINK_PATTERN,
_RICH_INLINE_LINK_PATTERN,
_RICH_REFERENCE_LINK_PATTERN,
)
return contains_accepted_rich_markdown_construct(
source,
UnsupportedConstruct.LINK_OR_IMAGE,
)


Expand Down Expand Up @@ -678,6 +700,78 @@ def unsupported_rich_markdown_inline(line: str) -> UnsupportedConstruct | None:
return None if construct is UnsupportedConstruct.LIST else construct


def contains_only_accepted_rich_markdown_inline(
source: str,
construct: UnsupportedConstruct,
) -> bool:
"""Return whether one accepted construct has no malformed inline peer."""

if type(source) is not str:
raise TypeError("rich Markdown inline validation requires exact text")
if not contains_accepted_rich_markdown_construct(source, construct):
return False
fence: str | None = None
fence_body_has_content = False
for line in source.splitlines():
marker = _RICH_FENCE_PATTERN.match(line)
if marker is not None:
candidate = marker.group("fence")
if fence is None:
fence = candidate
language = line.lstrip()[len(candidate) :].strip()
if len(language) > MARKDOWN_CODE_LANGUAGE_MAX_LENGTH or any(
character.isspace() for character in language
):
return False
fence_body_has_content = False
elif candidate[0] == fence[0] and len(candidate) >= len(fence):
if not fence_body_has_content:
return False
fence = None
Comment on lines +752 to +755

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Require a bare closing fence before handing off

When an otherwise accepted document contains a fenced block whose would-be closer has a suffix, such as ```oops, this condition treats that line as the closing fence because it checks only the marker character and length. The v3 parser's _is_closing_fence requires the marker to be followed only by whitespace, so the worker instead refuses the document as CODE_BLOCK; the preview therefore returns an actionable scan handoff for malformed syntax that ADR-0093 says must remain generically unavailable. Validate the complete closing-fence line using the same rule as the v3 parser.

AGENTS.md reference: AGENTS.md:L22-L24

Useful? React with 👍 / 👎.

continue
if fence is not None:
fence_body_has_content = fence_body_has_content or bool(line.strip())
continue
Comment on lines +766 to +779

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject indented separators while a list is open

stometa, when an accepted rich construct is followed by a list continuation such as - item\n ordinary\n ---, this branch treats the indented separator as a standalone setext/thematic marker and returns a scan handoff. The v3 parser instead processes it as an indented list continuation and refuses it as FRONTMATTER_OR_RULE, so malformed input bypasses the ADR-0093 requirement that compilation refusals remain generically unavailable. Check list-continuation context before handling setext and thematic separators.

AGENTS.md reference: AGENTS.md:L22-L24

Useful? React with 👍 / 👎.

if (
_THEMATIC_BREAK_PATTERN.fullmatch(line) is not None
or _RICH_SETEXT_PATTERN.fullmatch(line) is not None
):
continue
stripped = line.strip()
if stripped.startswith("<"):
if _RICH_ANGLE_LITERAL_PATTERN.fullmatch(stripped) is not None:
continue
if not _has_closed_rich_html_block(line, source):
return False
continue
inspected = _rich_markdown_inline_payload(line)
if unsupported_rich_markdown_inline(inspected) is not None:
return False
return fence is None
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved


def _rich_markdown_inline_payload(line: str) -> str:
inspected = line
if (heading := _RICH_ATX_HEADING_PATTERN.fullmatch(line)) is not None:
inspected = heading.group(2).strip()
elif (item := _RICH_LIST_ITEM_PATTERN.fullmatch(line)) is not None:
inspected = item.group(2)
elif line.lstrip().startswith(">"):
inspected = line.lstrip()[1:].lstrip()
if inspected.startswith("[!"):
inspected = _RICH_FOOTNOTE_PATTERN.sub("x", inspected, count=1)
return inspected


def _has_closed_rich_html_block(line: str, source: str) -> bool:
html_open = _RICH_HTML_OPEN_PATTERN.match(line)
return html_open is not None and re.search(
rf"</{re.escape(html_open.group('tag'))}[ \t]*>",
source,
re.IGNORECASE,
) is not None


@dataclass(frozen=True, slots=True)
class CompilationFailure:
"""Typed all-or-nothing failure; it never carries partial ParsedDocument data."""
Expand Down Expand Up @@ -1356,15 +1450,7 @@ def _validate_rich_closed_grammar(section: ParsedSection, source: str) -> None:
return
if len(lines) >= 2 and lines[0] == "---" and lines[-1] == "---":
return
html_open = _RICH_HTML_OPEN_PATTERN.match(lines[0]) if lines else None
if (
html_open is not None
and re.search(
rf"</{html_open.group('tag')}[ \t]*>",
source,
re.IGNORECASE,
)
):
if lines and _has_closed_rich_html_block(lines[0], source):
return
if (
section.kind is SectionKind.PARAGRAPH
Expand Down Expand Up @@ -1395,23 +1481,14 @@ def _validate_rich_closed_grammar(section: ParsedSection, source: str) -> None:
raise ValueError("rich section source must match the closed grammar")
return
for line in lines:
inspected = line
if section.kind is SectionKind.HEADING:
match = _RICH_ATX_HEADING_PATTERN.fullmatch(line)
if match is not None:
inspected = match.group(2).strip()
elif _RICH_SETEXT_PATTERN.fullmatch(line) is not None:
continue
elif section.kind is SectionKind.LIST:
match = _RICH_LIST_ITEM_PATTERN.fullmatch(line)
if match is not None:
inspected = match.group(2)
elif line.startswith((" ", "\t")):
inspected = line.lstrip()
elif line.lstrip().startswith(">"):
inspected = line.lstrip()[1:].lstrip()
if inspected.startswith("[!"):
inspected = _RICH_FOOTNOTE_PATTERN.sub("x", inspected, count=1)
if (
section.kind is SectionKind.HEADING
and _RICH_SETEXT_PATTERN.fullmatch(line) is not None
):
continue
inspected = _rich_markdown_inline_payload(line)
if section.kind is SectionKind.LIST and line.startswith((" ", "\t")):
inspected = inspected.lstrip()
if unsupported_rich_markdown_inline(inspected) is not None:
raise ValueError("rich section source must match the closed grammar")

Expand Down
36 changes: 34 additions & 2 deletions tests/integration/test_import_preview_requires_confirm.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,9 +134,16 @@ def _ui_import_scenario(
b"# Handbook\n\nEmbed ![[private-runbook]].\n",
b"# Handbook\n\nRead <https://private.invalid/runbook>.\n",
b"# Handbook\n\nFirst paragraph.\n\nRead [[private-runbook]].\n",
b"# Handbook\n\n- Read [[private-runbook]].\n",
b"# Handbook\n\nOnly *emphasis*.\n",
b"# Handbook\n\nOnly `inline code`.\n",
b"# Handbook\n\nOnly ~~strikethrough~~.\n",
b"# Handbook\n\n*Accepted*\n\n<section>\n",
b"# Handbook\n\nOnly *emphasis*.\n\n---\n",
b"*Emphasized heading*\n---\n",
],
)
def test_link_bearing_import_preview_hands_off_to_the_leased_scan_path(
def test_v3_only_import_preview_hands_off_to_the_leased_scan_path(
tmp_path: Path,
migration_configuration: DatabaseConfiguration,
guarded_control_engine: Engine,
Expand Down Expand Up @@ -213,18 +220,43 @@ def test_link_bearing_import_preview_hands_off_to_the_leased_scan_path(
assert published_count == 0


@pytest.mark.parametrize(
"payload",
[
b"# Handbook\n\n[[private-runbook]]\xffprivate malformed body\n",
b"# Handbook\n\nOnly `private malformed body.\n",
b"# Handbook\n\nOnly ~~private malformed body.\n",
b"# Handbook\n\n*Accepted* plus ~~private malformed body.\n",
b"# Handbook\n\n`Accepted` plus ~~private malformed body.\n",
b"# Handbook\n\n~~Accepted~~ plus `private malformed body.\n",
b"# Handbook\n\n[Accepted](note.md) plus ~~private malformed body.\n",
b"# Handbook\n\n[[Accepted]] plus `private malformed body.\n",
b"# Handbook\n\n- [Accepted](note.md) plus `private malformed body.\n",
b"# Handbook\n\n> [[Accepted]] plus `private malformed body.\n",
b"# Handbook\n\n## [Accepted](note.md) plus `private malformed body.\n",
(
b"# Handbook\n\n[Accepted](note.md)\n\n```"
+ b"x" * 65
+ b"\nbody\n```\n"
),
b"# Handbook\n\n[Accepted](note.md)\n\n```text\n\n```\n",
b"# Handbook\n\n*Accepted*\n\n<private malformed body\n",
b"# Handbook\n\n*Accepted*\n\n<div>unclosed\n",
],
)
def test_malformed_import_refusal_stays_content_free_without_scan_handoff(
tmp_path: Path,
migration_configuration: DatabaseConfiguration,
guarded_control_engine: Engine,
guarded_runtime_engine: Engine,
payload: bytes,
) -> None:
with _ui_import_scenario(
tmp_path=tmp_path,
migration_configuration=migration_configuration,
guarded_control_engine=guarded_control_engine,
guarded_runtime_engine=guarded_runtime_engine,
payload=b"# Handbook\n\n[[private-runbook]]\xffprivate malformed body\n",
payload=payload,
) as (scenario, client, _migration_engine):
response = client.post(
"/ui/import/preview",
Expand Down
Loading
Loading