Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

修复深度研究报告润色问题

weixin_4578200551f57c75fe6d
diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/cjk_friendly_emphasis.py b/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/cjk_friendly_emphasis.py
new file mode 100644
index 0000000000..3fc92625d5
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/cjk_friendly_emphasis.py
@@ -0,0 +1,282 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+#
+# This file is a Python port of the attention/strikethrough semantics of:
+# micromark-extension-cjk-friendly and micromark-extension-cjk-friendly-util
+# Copyright (c) Tatsunori Uchino (https://github.com/tats-u)
+# Licensed under the MIT License (https://opensource.org/licenses/MIT)
+"""CJK-friendly emphasis and strikethrough flanking for markdown-it-py.
+
+Ports the attention semantics of the relay-claw frontend parser stack
+(remark-cjk-friendly + remark-cjk-friendly-gfm-strikethrough, i.e.
+micromark-extension-cjk-friendly and its util) onto markdown-it-py by
+swapping the emphasis/strikethrough inline rules on one parser instance for
+variants whose ``scanDelims`` is the CJK-friendly port below.
+
+Why: the deepresearch rewrite map must classify as rewritable exactly the
+paragraphs the frontend selection code does. Both sides decide whether a
+delimiter run can open/close emphasis from the characters adjacent to the
+run, but they disagree on CJK text: with strict CommonMark a closing ``**``
+preceded by CJK punctuation (``**要点。**的``) is not right-flanking, so
+markdown-it leaves the run literal and produces nested/mismatched strong
+pairs, which makes the inline scanner reject the whole paragraph as
+``unsupported_inline`` while the CJK-friendly frontend parses one flat
+strong. Selections then fail with UNSUPPORTED_SELECTION.
+
+The delimiter pairing algorithm (``markdown_it.rules_inline.balance_pairs``,
+including the rule of three) is untouched — CommonMark attention matching is
+identical on both sides. Only the character classification feeding
+``can_open``/``can_close`` differs, and that is exactly what ``scanDelims``
+computes. Character data comes from ``cjk_unicode_tables``, generated from
+the frontend's own classification functions to avoid Unicode-version drift.
+
+Differences from stock markdown-it scanDelims (all inherited from the
+micromark forks):
+
+- CJK punctuation does not count as punctuation for flanking, so
+ ``**要点。**`` and ``文本**要点**`` parse as strong on both sides.
+- A run adjacent to CJK/IVS characters can open/close even next to
+ non-CJK punctuation.
+- A run whose neighbor is another attention marker (``*``/``_``/``~``)
+ always can open/close (micromark behavior; stock markdown-it lacks this).
+- ``_``'s intraword restriction consults "space or punctuation", where CJK
+ punctuation counts as punctuation.
+
+Known, accepted divergence: the frontend allows single-tilde strikethrough
+(``~x~``; singleTilde defaults to true in the micromark fork) while
+markdown-it requires ``~~``. A lone ``~`` stays literal text on this side;
+that predates the CJK work and only affects rare tilde runs.
+
+Scoping: :func:`apply_cjk_friendly_rules` swaps the rules on one parser
+instance only. Every other ``MarkdownIt`` in the process — including
+``document_rewrite._INLINE_PARSER`` and any instance a future module or
+third-party library creates — keeps stock CommonMark flanking, so the
+parsing difference cannot leak across modules. The swapped rules delegate to
+the stock ``markdown_it.rules_inline`` tokenize functions with
+``scanDelims`` shadowed on that single parse's ``StateInline`` (restored
+immediately after the rule returns; no class-level or process-global state
+is modified), so no markdown-it-py code is duplicated here and the rules
+automatically follow the installed package version.
+"""
+from __future__ import annotations
+
+from types import MethodType
+
+from markdown_it import MarkdownIt
+from markdown_it.rules_inline import emphasis, strikethrough
+from markdown_it.rules_inline.state_inline import Scanned, StateInline
+
+from jiuwenswarm.agents.harness.common.tools.deepresearch_plugin.cjk_unicode_tables import (
+ CJK,
+ CJK_AMBIGUOUS_PUNCTUATION_QUOTES,
+ IVS,
+ NON_EMOJI_GENERAL_USE_VS_RANGE,
+ PUNCTUATION,
+ WHITESPACE_CHARS,
+)
+
+# Character-group bitmasks, mirroring micromark-util-symbol (whitespace=1,
+# punctuation=2) and micromark-extension-cjk-friendly-util constantsEx.
+_WHITESPACE = 1
+_PUNCTUATION = 2
+_CJK = 4096
+_CJK_PUNCTUATION = _CJK | _PUNCTUATION # constantsEx.cjkPunctuation
+_IVS = 8192
+_NON_EMOJI_GENERAL_USE_VS = 16384
+
+# Attention markers after the frontend extensions are combined: core '*'/'_'
+# plus '~' from remark-cjk-friendly-gfm-strikethrough.
+_ATTENTION_MARKERS = frozenset("*_~")
+
+# U+FE01 — the variation selector that flips curly quotes to CJK punctuation
+# (isCjkAmbiguousPunctuation in the util source).
+_VARIATION_SELECTOR_1 = 0xFE01
+
+# CJK classification only applies from U+1100 (Hangul Jamo) upward, matching
+# the `code >= 4352` guard in the util's classifyCharacter.
+_MIN_CJK_CODE_POINT = 4352
+
+
+def _classify_character(ch: str | None) -> int:
+ """Port of the util's classifyCharacter.
+
+ eof (``None``) and JavaScript ``\\s`` characters — which subsume the
+ markdown line endings — classify as whitespace. A character can be both
+ CJK and punctuation; that combination is the whole point.
+ """
+ if ch is None or ch in WHITESPACE_CHARS:
+ return _WHITESPACE
+ code_point = ord(ch)
+ value = 0
+ if code_point >= _MIN_CJK_CODE_POINT:
+ low, high = NON_EMOJI_GENERAL_USE_VS_RANGE
+ if low <= code_point <= high:
+ return _NON_EMOJI_GENERAL_USE_VS
+ if code_point in IVS:
+ return _IVS
+ if code_point in CJK:
+ value |= _CJK
+ if code_point in PUNCTUATION:
+ value |= _PUNCTUATION
+ return value
+
+
+def _classify_preceding_character(
+ before: int, previous: str, two_previous: str | None
+) -> int:
+ """Port of the util's classifyPrecedingCharacter.
+
+ When the character before the run is a non-emoji general-use variation
+ selector (U+FE00..U+FE0E), its effective group is resolved from the
+ character before it. ``two_previous`` is ``None`` at line starts, matching
+ the chunked-buffer boundary in the micromark forks.
+ """
+ if before != _NON_EMOJI_GENERAL_USE_VS:
+ return before
+ two_before = _classify_character(two_previous)
+ if not two_previous or two_before & _WHITESPACE:
+ return before
+ if (
+ ord(previous) == _VARIATION_SELECTOR_1
+ and ord(two_previous) in CJK_AMBIGUOUS_PUNCTUATION_QUOTES
+ ):
+ return _CJK_PUNCTUATION
+ return two_before & ~_IVS
+
+
+def _is_unicode_whitespace(category: int) -> bool:
+ return bool(category & _WHITESPACE)
+
+
+def _is_non_cjk_punctuation(category: int) -> bool:
+ # Punctuation bit set without the CJK bit: exactly the non-CJK subset.
+ return (category & _CJK_PUNCTUATION) == _PUNCTUATION
+
+
+def _is_cjk(category: int) -> bool:
+ return bool(category & _CJK)
+
+
+def _is_cjk_or_ivs(category: int) -> bool:
+ return bool(category & (_CJK | _IVS))
+
+
+def _is_space_or_punctuation(category: int) -> bool:
+ # Used by the '_' intraword rule; CJK punctuation keeps its punct bit here.
+ return bool(category & (_WHITESPACE | _PUNCTUATION))
+
+
+def _cjk_scan_delims(state: StateInline, start: int, can_split_word: bool) -> Scanned:
+ """CJK-friendly port of ``StateInline.scanDelims`` for attention markers.
+
+ Callers (the two rules below) guarantee ``state.src[start]`` is one of
+ ``*``/``_``/``~``. ``can_split_word`` is kept for signature compatibility
+ with stock ``scanDelims`` (markdown-it-py names it ``canSplitWord``; both
+ rules pass it positionally); the branches below key off the marker
+ character, mirroring how the micromark forks define separate attention
+ ('*'/'_') and strikethrough ('~') tokenizers.
+ """
+ marker = state.src[start]
+
+ pos = start
+ maximum = state.posMax
+ while pos < maximum and state.src[pos] == marker:
+ pos += 1
+ count = pos - start
+
+ # Neighbors as full code points: Python strings are scalar values, so the
+ # UTF-16 surrogate gymnastics of the micromark forks is unnecessary.
+ previous = state.src[start - 1] if start > 0 else None
+ after = state.src[pos] if pos < maximum else None
+ two_previous = (
+ state.src[start - 2] if start >= 2 and state.src[start - 2] != "\n" else None
+ )
+
+ before_raw = _classify_character(previous)
+ before_primary = _classify_preceding_character(before_raw, previous, two_previous)
+ after_category = _classify_character(after)
+
+ before_non_cjk_punct = _is_non_cjk_punctuation(before_primary)
+ before_space_or_non_cjk_punct = before_non_cjk_punct or _is_unicode_whitespace(
+ before_primary
+ )
+ after_non_cjk_punct = _is_non_cjk_punctuation(after_category)
+ after_space_or_non_cjk_punct = after_non_cjk_punct or _is_unicode_whitespace(
+ after_category
+ )
+
+ if marker == "~":
+ # Strikethrough fork: same flanking idea, no attention-marker clause,
+ # and the closing punct test reads the raw (not resolved) before-group.
+ before_cjk_or_ivs = _is_cjk(before_primary) or before_raw == _IVS
+ can_open = not after_space_or_non_cjk_punct or (
+ after_category == _PUNCTUATION
+ and (before_space_or_non_cjk_punct or before_cjk_or_ivs)
+ )
+ can_close = not before_space_or_non_cjk_punct or (
+ before_raw == _PUNCTUATION
+ and (after_space_or_non_cjk_punct or _is_cjk(after_category))
+ )
+ return Scanned(can_open, can_close, count)
+
+ # Attention fork ('*' and '_').
+ before_cjk_or_ivs = _is_cjk_or_ivs(before_primary)
+ open_ = (
+ not after_space_or_non_cjk_punct
+ or (
+ after_non_cjk_punct
+ and (before_space_or_non_cjk_punct or before_cjk_or_ivs)
+ )
+ or after in _ATTENTION_MARKERS
+ )
+ close_ = (
+ not before_space_or_non_cjk_punct
+ or (
+ before_non_cjk_punct
+ and (after_space_or_non_cjk_punct or _is_cjk(after_category))
+ )
+ or previous in _ATTENTION_MARKERS
+ )
+ if marker == "*":
+ return Scanned(open_, close_, count)
+ # '_' intraword rule (emphasis.tokenize passes can_split_word=False for '_').
+ can_open = open_ and (_is_space_or_punctuation(before_primary) or not close_)
+ can_close = close_ and (_is_space_or_punctuation(after_category) or not open_)
+ return Scanned(can_open, can_close, count)
+
+
+def _cjk_emphasis_tokenize(state: StateInline, silent: bool) -> bool:
+ """Stock ``emphasis.tokenize`` with this parse's ``scanDelims`` CJK-friendly.
+
+ Shadows ``scanDelims`` on the state object for the duration of the stock
+ rule only — per-parse and per-thread; the class and the process are
+ never modified — so the markdown-it-py rule body is reused as installed
+ instead of being copied into this repository.
+ """
+ state.scanDelims = MethodType(_cjk_scan_delims, state)
+ try:
+ return emphasis.tokenize(state, silent)
+ finally:
+ del state.scanDelims
+
+
+def _cjk_strikethrough_tokenize(state: StateInline, silent: bool) -> bool:
+ """Stock ``strikethrough.tokenize`` with this parse's ``scanDelims`` CJK-friendly.
+
+ Same per-parse shadowing as :func:`_cjk_emphasis_tokenize`.
+ """
+ state.scanDelims = MethodType(_cjk_scan_delims, state)
+ try:
+ return strikethrough.tokenize(state, silent)
+ finally:
+ del state.scanDelims
+
+
+def apply_cjk_friendly_rules(parser: MarkdownIt) -> MarkdownIt:
+ """Swap emphasis/strikethrough rules on ``parser`` for CJK-friendly ones.
+
+ Instance-scoped: only ``parser`` changes behavior; every other
+ ``MarkdownIt`` instance in the process keeps stock CommonMark flanking.
+ """
+ parser.inline.ruler.at("emphasis", _cjk_emphasis_tokenize)
+ parser.inline.ruler.at("strikethrough", _cjk_strikethrough_tokenize)
+ return parser
diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/cjk_unicode_tables.py b/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/cjk_unicode_tables.py
new file mode 100644
index 0000000000..73d5232c7c
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/cjk_unicode_tables.py
@@ -0,0 +1,142 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+#
+# Classification data generated by executing:
+# micromark-extension-cjk-friendly-util (Copyright (c) Tatsunori Uchino,
+# https://github.com/tats-u, MIT License) and its dependency
+# get-east-asian-width (Copyright (c) Sindre Sorhus, MIT License).
+r"""Unicode classification tables for CJK-friendly Markdown emphasis parsing.
+
+GENERATED FILE — do not edit by hand.
+
+Regenerated by scanning every Unicode scalar value through the exact functions
+the relay-claw frontend uses (micromark-extension-cjk-friendly-util 3.0.1, via
+get-east-asian-width 1.6.0, under Node 22/V8):
+
+- ``unicodePunctuation`` — ``/\p{P}|\p{S}/u`` (CommonMark 0.31 "Unicode
+ punctuation": general categories P* and S*)
+- ``unicodeWhitespace`` — JavaScript ``/\s/`` (note: NOT CommonMark whitespace;
+ it includes VT and U+FEFF but excludes U+0085)
+- ``cjkOrIvs`` — East Asian Width fullwidth/halfwidth/wide (minus
+ Emoji_Presentation) plus Hangul
+
+Generating from the live package instead of re-deriving from Python's
+``unicodedata`` pins the sidecar to the frontend's exact character data and
+avoids Unicode-version drift between the two runtimes.
+"""
+from __future__ import annotations
+
+from bisect import bisect_right
+
+# Code-point ranges where the frontend's `unicodePunctuation` is true.
+PUNCTUATION_RANGES: tuple[tuple[int, int], ...] = (
+ (33, 47), (58, 64), (91, 96), (123, 126), (161, 169), (171, 172), (174, 177), (180, 180), (182, 184),
+ (187, 187), (191, 191), (215, 215), (247, 247), (706, 709), (722, 735), (741, 747), (749, 749),
+ (751, 767), (885, 885), (894, 894), (900, 901), (903, 903), (1014, 1014), (1154, 1154), (1370, 1375),
+ (1417, 1418), (1421, 1423), (1470, 1470), (1472, 1472), (1475, 1475), (1478, 1478), (1523, 1524),
+ (1542, 1551), (1563, 1563), (1565, 1567), (1642, 1645), (1748, 1748), (1758, 1758), (1769, 1769),
+ (1789, 1790), (1792, 1805), (2038, 2041), (2046, 2047), (2096, 2110), (2142, 2142), (2184, 2184),
+ (2404, 2405), (2416, 2416), (2546, 2547), (2554, 2555), (2557, 2557), (2678, 2678), (2800, 2801),
+ (2928, 2928), (3059, 3066), (3191, 3191), (3199, 3199), (3204, 3204), (3407, 3407), (3449, 3449),
+ (3572, 3572), (3647, 3647), (3663, 3663), (3674, 3675), (3841, 3863), (3866, 3871), (3892, 3892),
+ (3894, 3894), (3896, 3896), (3898, 3901), (3973, 3973), (4030, 4037), (4039, 4044), (4046, 4058),
+ (4170, 4175), (4254, 4255), (4347, 4347), (4960, 4968), (5008, 5017), (5120, 5120), (5741, 5742),
+ (5787, 5788), (5867, 5869), (5941, 5942), (6100, 6102), (6104, 6107), (6144, 6154), (6464, 6464),
+ (6468, 6469), (6622, 6655), (6686, 6687), (6816, 6822), (6824, 6829), (6990, 6991), (7002, 7018),
+ (7028, 7039), (7164, 7167), (7227, 7231), (7294, 7295), (7360, 7367), (7379, 7379), (8125, 8125),
+ (8127, 8129), (8141, 8143), (8157, 8159), (8173, 8175), (8189, 8190), (8208, 8231), (8240, 8286),
+ (8314, 8318), (8330, 8334), (8352, 8384), (8448, 8449), (8451, 8454), (8456, 8457), (8468, 8468),
+ (8470, 8472), (8478, 8483), (8485, 8485), (8487, 8487), (8489, 8489), (8494, 8494), (8506, 8507),
+ (8512, 8516), (8522, 8525), (8527, 8527), (8586, 8587), (8592, 9257), (9280, 9290), (9372, 9449),
+ (9472, 10101), (10132, 11123), (11126, 11157), (11159, 11263), (11493, 11498), (11513, 11516),
+ (11518, 11519), (11632, 11632), (11776, 11822), (11824, 11869), (11904, 11929), (11931, 12019),
+ (12032, 12245), (12272, 12287), (12289, 12292), (12296, 12320), (12336, 12336), (12342, 12343),
+ (12349, 12351), (12443, 12444), (12448, 12448), (12539, 12539), (12688, 12689), (12694, 12703),
+ (12736, 12773), (12783, 12783), (12800, 12830), (12842, 12871), (12880, 12880), (12896, 12927),
+ (12938, 12976), (12992, 13311), (19904, 19967), (42128, 42182), (42238, 42239), (42509, 42511),
+ (42611, 42611), (42622, 42622), (42738, 42743), (42752, 42774), (42784, 42785), (42889, 42890),
+ (43048, 43051), (43062, 43065), (43124, 43127), (43214, 43215), (43256, 43258), (43260, 43260),
+ (43310, 43311), (43359, 43359), (43457, 43469), (43486, 43487), (43612, 43615), (43639, 43641),
+ (43742, 43743), (43760, 43761), (43867, 43867), (43882, 43883), (44011, 44011), (64297, 64297),
+ (64434, 64450), (64830, 64847), (64975, 64975), (65020, 65023), (65040, 65049), (65072, 65106),
+ (65108, 65126), (65128, 65131), (65281, 65295), (65306, 65312), (65339, 65344), (65371, 65381),
+ (65504, 65510), (65512, 65518), (65532, 65533), (65792, 65794), (65847, 65855), (65913, 65929),
+ (65932, 65934), (65936, 65948), (65952, 65952), (66000, 66044), (66463, 66463), (66512, 66512),
+ (66927, 66927), (67671, 67671), (67703, 67704), (67871, 67871), (67903, 67903), (68176, 68184),
+ (68223, 68223), (68296, 68296), (68336, 68342), (68409, 68415), (68505, 68508), (68974, 68974),
+ (69006, 69007), (69293, 69293), (69461, 69465), (69510, 69513), (69703, 69709), (69819, 69820),
+ (69822, 69825), (69952, 69955), (70004, 70005), (70085, 70088), (70093, 70093), (70107, 70107),
+ (70109, 70111), (70200, 70205), (70313, 70313), (70612, 70613), (70615, 70616), (70731, 70735),
+ (70746, 70747), (70749, 70749), (70854, 70854), (71105, 71127), (71233, 71235), (71264, 71276),
+ (71353, 71353), (71484, 71487), (71739, 71739), (72004, 72006), (72162, 72162), (72255, 72262),
+ (72346, 72348), (72350, 72354), (72448, 72457), (72673, 72673), (72769, 72773), (72816, 72817),
+ (73463, 73464), (73539, 73551), (73685, 73713), (73727, 73727), (74864, 74868), (77809, 77810),
+ (92782, 92783), (92917, 92917), (92983, 92991), (92996, 92997), (93549, 93551), (93847, 93850),
+ (94178, 94178), (113820, 113820), (113823, 113823), (117760, 117999), (118016, 118451), (118608, 118723),
+ (118784, 119029), (119040, 119078), (119081, 119140), (119146, 119148), (119171, 119172),
+ (119180, 119209), (119214, 119274), (119296, 119361), (119365, 119365), (119552, 119638),
+ (120513, 120513), (120539, 120539), (120571, 120571), (120597, 120597), (120629, 120629),
+ (120655, 120655), (120687, 120687), (120713, 120713), (120745, 120745), (120771, 120771),
+ (120832, 121343), (121399, 121402), (121453, 121460), (121462, 121475), (121477, 121483),
+ (123215, 123215), (123647, 123647), (124415, 124415), (125278, 125279), (126124, 126124),
+ (126128, 126128), (126254, 126254), (126704, 126705), (126976, 127019), (127024, 127123),
+ (127136, 127150), (127153, 127167), (127169, 127183), (127185, 127221), (127245, 127405),
+ (127462, 127490), (127504, 127547), (127552, 127560), (127568, 127569), (127584, 127589),
+ (127744, 128727), (128732, 128748), (128752, 128764), (128768, 128886), (128891, 128985),
+ (128992, 129003), (129008, 129008), (129024, 129035), (129040, 129095), (129104, 129113),
+ (129120, 129159), (129168, 129197), (129200, 129211), (129216, 129217), (129280, 129619),
+ (129632, 129645), (129648, 129660), (129664, 129673), (129679, 129734), (129742, 129756),
+ (129759, 129769), (129776, 129784), (129792, 129938), (129940, 130031),
+)
+
+# Code-point ranges the frontend's `cjkOrIvs` classifies as CJK.
+CJK_RANGES: tuple[tuple[int, int], ...] = (
+ (4352, 4607), (8361, 8361), (9001, 9002), (9776, 9783), (9866, 9871), (11904, 11929), (11931, 12019),
+ (12032, 12245), (12272, 12350), (12353, 12438), (12441, 12543), (12549, 12591), (12593, 12686),
+ (12688, 12773), (12783, 12830), (12832, 12871), (12880, 42124), (42128, 42182), (43360, 43388),
+ (44032, 55203), (55216, 55238), (55243, 55291), (63744, 64255), (65040, 65049), (65072, 65106),
+ (65108, 65126), (65128, 65131), (65281, 65470), (65474, 65479), (65482, 65487), (65490, 65495),
+ (65498, 65500), (65504, 65510), (65512, 65518), (94176, 94180), (94192, 94198), (94208, 101589),
+ (101631, 101662), (101760, 101874), (110576, 110579), (110581, 110587), (110589, 110590),
+ (110592, 110882), (110898, 110898), (110928, 110930), (110933, 110933), (110948, 110951),
+ (110960, 111355), (119552, 119638), (119648, 119670), (127488, 127488), (127490, 127490),
+ (127504, 127513), (127515, 127534), (127536, 127537), (127543, 127543), (127547, 127547),
+ (127552, 127560), (127584, 127589), (128728, 128728), (129674, 129674), (129678, 129678),
+ (129736, 129736), (129741, 129741), (129770, 129770), (129775, 129775), (131072, 196605),
+ (196608, 262141),
+)
+
+# JavaScript `\s` — what the frontend's `unicodeWhitespace` actually tests.
+WHITESPACE_CHARS: frozenset[str] = frozenset(
+ "\t\n\x0b\x0c\r \u00a0\u1680\u2000\u2001"
+ "\u2002\u2003\u2004\u2005\u2006\u2007"
+ "\u2008\u2009\u200a\u2028\u2029\u202f"
+ "\u205f\u3000\ufeff"
+)
+
+# Fixed ranges hardcoded in the micromark-extension-cjk-friendly-util source
+# (cjkOrIvs returns None exactly on the standard IVS block; non-emoji
+# general-use variation selectors are U+FE00..U+FE0E, excluding emoji VS U+FE0F).
+IVS_RANGES: tuple[tuple[int, int], ...] = ((917760, 917999),) # U+E0100..U+E01EF
+NON_EMOJI_GENERAL_USE_VS_RANGE: tuple[int, int] = (65024, 65038) # U+FE00..U+FE0E
+# ' ' " " — reclassified CJK+Punct when followed by U+FE01
+# (isCjkAmbiguousPunctuation in the util source).
+CJK_AMBIGUOUS_PUNCTUATION_QUOTES: frozenset[int] = frozenset({8216, 8217, 8220, 8221})
+
+
+class _RangeTable:
+ """Constant code-point range table with bisect-based membership."""
+
+ __slots__ = ("_ranges", "_starts")
+
+ def __init__(self, ranges: tuple[tuple[int, int], ...]) -> None:
+ self._ranges = ranges
+ self._starts = tuple(start for start, _end in ranges)
+
+ def __contains__(self, code_point: int) -> bool:
+ index = bisect_right(self._starts, code_point) - 1
+ return index >= 0 and self._ranges[index][0] <= code_point <= self._ranges[index][1]
+
+
+PUNCTUATION = _RangeTable(PUNCTUATION_RANGES)
+CJK = _RangeTable(CJK_RANGES)
+IVS = _RangeTable(IVS_RANGES)
diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/document_rewrite.py b/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/document_rewrite.py
index e24da3c648..99817bcf8e 100644
--- a/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/document_rewrite.py
+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/document_rewrite.py
@@ -59,7 +59,7 @@ FORBIDDEN_OUTPUT_RE = re.compile(
LIST_RE = re.compile(r"^\s*(?:[-+*]|\d+[.)])\s+")
TOKEN_TTL_SECONDS = 10 * 60
CONTEXT_CACHE_MAX = 1024
-PROVENANCE_MAX_BYTES = 4 * 1024 * 1024
+PROVENANCE_MAX_BYTES = 8 * 1024 * 1024
FINAL_RESULT_MAX_BYTES = 64 * 1024 * 1024
MARKDOWN_MAX_BYTES = 64 * 1024 * 1024
CITATION_COUNT_MAX = 10_000
diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/markdown_rewrite_map.py b/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/markdown_rewrite_map.py
index 5a1c097c51..c1fba3400f 100644
--- a/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/markdown_rewrite_map.py
+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/markdown_rewrite_map.py
@@ -10,8 +10,28 @@ from typing import Literal
from urllib.parse import unquote
from markdown_it import MarkdownIt
+from markdown_it.common.entities import entities
+from markdown_it.common.utils import fromCodePoint, isValidEntityCode
from markdown_it.token import Token
+from jiuwenswarm.agents.harness.common.tools.deepresearch_plugin.cjk_friendly_emphasis import (
+ apply_cjk_friendly_rules,
+)
+
+
+def _new_rewrite_parser() -> MarkdownIt:
+ """Parser matching the relay-claw frontend's Markdown semantics.
+
+ The rewrite map must classify exactly the paragraphs the frontend
+ selection code treats as rewritable, so this parser carries the
+ frontend's CJK-friendly emphasis rules (instance-scoped; all other
+ MarkdownIt instances keep stock CommonMark flanking). See
+ cjk_friendly_emphasis for details.
+ """
+ return apply_cjk_friendly_rules(
+ MarkdownIt("commonmark", {"html": True}).enable(["table", "strikethrough"])
+ )
+
UnitType = Literal["heading", "paragraph", "list_item"]
ProtectedKind = Literal[
@@ -304,6 +324,50 @@ def _encode_markdown_literal(text: str) -> str:
_UNMATCHED_CONSTRUCT_PREFIXES = ("**", "__", "~~", "[", "]", "<", "`", "![")
+# Constructs that are ordinary literal text whenever markdown-it left them
+# inside a text token — reference-list labels (`[1]. `), LaTeX-ish math
+# (`$β<0.6$`), unpaired brackets or backticks. The relay-claw frontend
+# accepts such paragraphs as rewritable, so an odd count must not reject the
+# whole unit; the per-character raw/visible alignment below already
+# guarantees the token is an exact source slice. Emphasis markers keep the
+# odd-count fail-closed rule above.
+_LITERAL_TEXT_CONSTRUCTS = frozenset({"[", "]", "<", "`", "!["})
+
+# CommonMark character references — same shapes markdown-it's own entity rule
+# decodes (rules_inline/entity.py) before `text_join` merges them into text
+# tokens, which is why rendered text can carry a character whose raw source
+# form is multi-byte (e.g. `&#91;` for `[` in scraped reference titles).
+_ENTITY_DIGITAL_RE = re.compile(r"&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));", re.IGNORECASE)
+_ENTITY_NAMED_RE = re.compile(r"&([a-z][a-z0-9]{1,31});", re.IGNORECASE)
+
+
+def _decode_entity_at(raw: str, index: int) -> tuple[str, int] | None:
+ """Decode a single-character CommonMark reference at ``raw[index:]``.
+
+ Returns ``(decoded character, raw length)``, or ``None`` when the source
+ does not hold a valid entity there (mirrors rules_inline/entity.py) or
+ the entity decodes to more than one code point (HTML5 named ligatures
+ and combining sequences such as ``&fjlig;`` -> "fj"; those fail closed
+ so consumers never align only the first code point of an entity).
+ """
+ if index >= len(raw) or raw[index] != "&":
+ return None
+ tail = raw[index:]
+ if len(tail) > 1 and tail[1] == "#":
+ match = _ENTITY_DIGITAL_RE.match(tail)
+ if match is not None:
+ digits = match.group(1)
+ code = int(digits[1:], 16) if digits[0].lower() == "x" else int(digits, 10)
+ char = fromCodePoint(code) if isValidEntityCode(code) else fromCodePoint(0xFFFD)
+ return char, match.end()
+ else:
+ match = _ENTITY_NAMED_RE.match(tail)
+ if match is not None and match.group(1) in entities:
+ decoded = entities[match.group(1)]
+ if len(decoded) == 1:
+ return decoded, match.end()
+ return None
+
def _matched_unmatched_construct(raw: str, index: int) -> str | None:
tail = raw[index:]
@@ -391,8 +455,8 @@ class _InlineScanner:
) -> None:
if not rendered:
return
- # CommonMark flanking rules can leave a balanced, paired `**`/`__`/`~~`
- # as literal text inside a text token (e.g. `每周**≤2次**。`, where the
+ # Flanking rules can leave a balanced, paired `**`/`__`/`~~` as
+ # literal text inside a text token (e.g. `x**≤**y`, where the Latin
# opener is followed by the punctuation `≤`). markdown-it has already
# decided these are literal, so consuming them as text preserves the
# lossless invariant. Only genuinely unbalanced markers (odd count,
@@ -411,12 +475,19 @@ class _InlineScanner:
and self.raw[self.cursor + 1] in _ESCAPABLE
and self.raw[self.cursor + 1] == visible
)
+ entity = _decode_entity_at(self.raw, self.cursor)
if is_escaped_visible:
self.cursor += 2
+ elif entity is not None and entity[0] == visible:
+ # Character references: one visible char spanning several raw
+ # bytes (`&#91;` renders as `[`). Consumed whole so slots stay
+ # exact source slices.
+ self.cursor += entity[1]
elif self.cursor < len(self.raw) and self.raw[self.cursor] == visible:
construct = _matched_unmatched_construct(self.raw, self.cursor)
if (
construct is not None
+ and construct not in _LITERAL_TEXT_CONSTRUCTS
and construct not in balanced_double_markers
):
raise _InlineTopologyError("unmatched inline marker")
@@ -723,9 +794,7 @@ def _list_item_kind(tokens: list[Token], open_index: int, close_index: int) -> s
def build_rewrite_map(markdown: str) -> MarkdownRewriteMap:
"""Classify blocks and map supported inline text to exact source bytes."""
boundary_table = Utf8BoundaryTable(markdown)
- parser = MarkdownIt("commonmark", {"html": True}).enable(
- ["table", "strikethrough"]
- )
+ parser = _new_rewrite_parser()
tokens = parser.parse(markdown)
source_lines = _SourceLines(markdown)
units: list[RewriteUnit] = []
@@ -916,9 +985,7 @@ def _heading_visible_text(inline: Token) -> tuple[str, bool]:
def build_document_anchor_index(markdown: str) -> DocumentAnchorIndex:
"""Index headings and same-document links across supported and unsupported blocks."""
- parser = MarkdownIt("commonmark", {"html": True}).enable(
- ["table", "strikethrough"]
- )
+ parser = _new_rewrite_parser()
tokens = parser.parse(markdown)
source_lines = _SourceLines(markdown)
boundaries = Utf8BoundaryTable(markdown)
@@ -1111,7 +1178,17 @@ def reconstruct_markdown(
soft_break = character == " " and re.fullmatch(
r"[ \t]*(?:\r\n|\r|\n)", raw_visible
)
- if not (literal or escaped or soft_break):
+ entity = (
+ _decode_entity_at(raw_visible, 0)
+ if raw_visible[:1] == "&"
+ else None
+ )
+ entity_visible = (
+ entity is not None
+ and entity[0] == character
+ and entity[1] == len(raw_visible)
+ )
+ if not (literal or escaped or soft_break or entity_visible):
conflict("slot visible text does not match its source bytes")
output.extend(source_bytes[start_byte:end_byte])
previous_end = end_byte
diff --git a/tests/unit_tests/agentserver/test_markdown_rewrite_map.py b/tests/unit_tests/agentserver/test_markdown_rewrite_map.py
index 4dd391b9da..4e4e468dd6 100644
--- a/tests/unit_tests/agentserver/test_markdown_rewrite_map.py
+++ b/tests/unit_tests/agentserver/test_markdown_rewrite_map.py
@@ -5,6 +5,7 @@ from dataclasses import FrozenInstanceError, replace
from pathlib import Path
import pytest
+from markdown_it import MarkdownIt
from jiuwenswarm.agents.harness.common.tools.deepresearch_plugin import (
markdown_rewrite_map as rewrite_map_module,
@@ -545,7 +546,6 @@ def test_crlf_inline_breaks_keep_exact_source_ranges(markdown, break_source):
"markdown",
[
"unterminated **strong",
- "[label](<bad destination)",
"<https://example.com>",
],
)
@@ -558,17 +558,77 @@ def test_ambiguous_inline_topology_fails_closed(markdown):
]
+def test_broken_link_destination_stays_supported_as_literal_text():
+ # A malformed angle-bracket destination emits no link tokens, so the whole
+ # span is literal text; `<` alone is not an unmatched construct. The
+ # relay-claw frontend accepts this paragraph, so the sidecar must too.
+ markdown = "[label](<bad destination)"
+
+ unit = rewrite_map_module.build_rewrite_map(markdown).units[0]
+
+ assert [slot.text for slot in unit.slots] == [markdown]
+ assert unit.protected == ()
+
+
+def test_named_entity_stays_supported_as_one_visible_character():
+ # `&le;` renders as one visible char spanning several raw bytes; the slot
+ # carries the decoded text while its byte range covers the entity source.
+ markdown = "浓度&le;0.5的溶液"
+
+ unit = rewrite_map_module.build_rewrite_map(markdown).units[0]
+
+ assert [slot.text for slot in unit.slots] == ["浓度≤0.5的溶液"]
+ assert unit.protected == ()
+
+
+def test_multi_codepoint_named_entity_fails_closed():
+ # HTML5 named entities can decode to several code points (`&fjlig;` ->
+ # "fj"). Aligning only the first code point would misattribute the rest
+ # to the source following the entity, so the unit fails closed instead.
+ markdown = "荷兰语连字&fjlig;示例"
+
+ rewrite_map = rewrite_map_module.build_rewrite_map(markdown)
+
+ assert rewrite_map.units == ()
+ assert [region.kind for region in rewrite_map.unsupported_regions] == [
+ "unsupported_inline"
+ ]
+
+
+def test_cjk_friendly_rules_do_not_leak_into_stock_parsers():
+ # The CJK-friendly flanking is registered per parser instance: a stock
+ # markdown-it keeps CommonMark semantics (the `**` stays literal next to
+ # CJK punctuation) while the rewrite parser pairs it like the frontend.
+ markdown = "**要点。**的"
+
+ stock = MarkdownIt("commonmark", {"html": True}).enable(
+ ["table", "strikethrough"]
+ )
+ inline = next(token for token in stock.parse(markdown) if token.type == "inline")
+ rewrite_slots = [
+ slot.text
+ for slot in rewrite_map_module.build_rewrite_map(markdown).units[0].slots
+ ]
+
+ assert [token.type for token in inline.children] == ["text"]
+ assert rewrite_slots == ["要点。", "的"]
+
+
@pytest.mark.parametrize(
("markdown", "expects_literal_stars"),
[
- # CommonMark flanking rules decline to treat a paired `**` as emphasis
- # when the opener is followed by punctuation (here the math symbol `<=`),
- # so markdown-it emits the `**` as literal text. The engine must consume
- # those literal markers as text instead of demoting the whole paragraph.
- ("每周**≤2次**。", True),
+ # With the frontend's CJK-friendly flanking rules, a CJK character
+ # before the opener lets `**` pair even when the follower is a
+ # non-CJK punctuation mark (the math symbol `<=`), so the markers are
+ # stripped as strong syntax — matching the relay-claw frontend.
+ ("每周**≤2次**。", False),
+ # A Latin word before the opener still cannot open next to
+ # punctuation, so markdown-it emits the `**` as literal text. The
+ # engine must consume those literal markers as text instead of
+ # demoting the whole paragraph.
("x**≤**y", True),
- # When flanking succeeds the `**` parses as emphasis and the markers are
- # stripped from the slot text; the paragraph is still supported.
+ # Intraword flanking succeeds and the markers are stripped from the
+ # slot text; the paragraph is still supported.
("a**b≤c**d", False),
],
)