Skip to content

fix: preserve literal final tags in delivered code examples - #138989

Merged
shakkernerd merged 4 commits into
openclaw:mainfrom
Alix-007:alix/fix-final-tag-code-literals-20260905
Sep 7, 2026
Merged

shakkernerd merged 4 commits into
openclaw:mainfrom
Alix-007:alix/fix-final-tag-code-literals-20260905

Conversation

@Alix-007

@Alix-007 Alix-007 commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Related: #133152 (the explicitly recorded final-delivery sanitizer follow-up).

What Problem This Solves

Fixes an issue where users receiving XML examples would lose literal <final> tags inside fenced or inline code when the reply passed through final delivery sanitization. The raw answer could contain the correct example while the delivered text silently changed it.

The merged maintainer-authored #133152 records this exact failed live scenario and leaves it as a named follow-up. This PR repairs that remaining behavior.

Why This Change Was Made

The final-tag owner now reuses the existing Markdown Core code regions, preserving literal code while removing control markers outside it. Ordered tag matches and code regions are traversed with one advancing cursor, avoiding a per-tag scan of every region. Reasoning cleanup delegates to this same owner instead of retaining its duplicate stripping loop; its original early-return and trimming conditions remain unchanged.

Existing-solutions preflight: OpenClaw already has the required CommonMark parser and code-region contract. No new parser, dependency, plugin, configuration, or alternative execution path is needed.

Production: +22/-14, net +8, across two files. Tests: +53, across three files. Documentation: +4 in the canonical Markdown formatting guide, clarifying the same boundary as the helper API comment. The production growth protects literal source text and bounds region lookup; the connected duplicate loop is removed. No changelog or proof assets are added to the product branch.

User Impact

Code examples retain their original XML tags. Real final-answer markers outside code are still removed without deleting the answer they enclose. Fenced, inline, indented, blockquoted, and unfinished fenced examples are covered, including attributed tags and mixed code/control text.

No config/default, protocol/schema, permissions, security-policy, persistence, migration, or upgrade change. This does not expose reasoning contents or relax private-scaffolding filtering; those are separate policies.

Evidence

Recorded CLI Behavior Receipt

  • Product head: 5654f5f36b2dadaab504060017d440cb858e6dc9.
  • Current PR head: c22b1b79cf975dc9335bb45dd19b19ac3e60203a. The recorded CLI receipt predates the behavior-equivalent cursor type correction and documentation/API-comment clarification. The latter emits identical JavaScript with comments removed; the CLI evidence remains applicable.
  • Baseline: 336b75a11d13bd173582dc7e3064b412c133bdcd. Both affected production files remain byte-identical on current main at the final pre-publication check.
  • Real entry: built OpenClaw CLI, using an isolated agent and the repository's existing loopback mock OpenAI server. The fixture explicitly selects the OpenClaw runtime, not Codex.
pnpm --silent openclaw agent --local --agent main \
  --session-id alix-final-tags-patched --channel telegram \
  --message "Return the fixture response exactly." \
  --thinking off --timeout 60 --json

No --deliver is supplied. The explicit channel selects real reply normalization without dispatching a channel message. The assertion reads canonical payloads[].text, not raw assistant metadata or a direct helper result.

  • Canonical owner exercised: agent command post-run delivery -> reply normalization -> sanitizeUserFacingText -> stripFinalTags.
  • Recorder/readback: actual CLI JSON output plus a recorded POST /v1/responses at the loopback provider. The receipt retains the exact command, input, expected/actual output, source SHA, session ID and observation time.
  • Acceptance red: baseline session alix-final-tags-baseline returned payload instead of <final data-model="demo">payload</final> inside the XML fence, and inline instead of <final>inline</final> inside inline code. Baseline run and logs.
  • Acceptance green: the same entry and fixture on product head preserve both examples byte-for-byte. Observed 2026-09-05T09:45:33.911Z, session alix-final-tags-patched. Exact-head run.
  • Legal control: <final>Outside answer</final> becomes Outside answer on both baseline and patched runs. The fixture combines this control with both literal-code cases in one reply.
  • Inspectable artifact: receipt, actual CLI output, test and formatting logs, cleanup receipt. Retained for 30 days. The baseline artifact upload excluded its hidden directory, so baseline evidence is in its retained run log; the patched upload explicitly includes it.
  • Reproduction driver: pinned isolated proof driver and workflow. These are fork-only evidence tooling, not part of this PR.
  • Cleanup and limitations: the owned mock process stopped and disposable state/workspace were removed. No production instance or external channel was touched. This proves real CLI/final-payload behavior with a mock provider, not a live provider, Telegram transport, or browser session.

Tests and Review

  • Baseline with the initial regression patch: 10 failed, 116 passed, with the failures demonstrating lost code literals.
  • Product head: 202 tests passed across final-tag owner, reasoning-tag sibling and user-facing sanitizer files. Includes outside-marker controls, literal-only whitespace trimming and 2,000 interleaved code regions.
  • Exact-head pnpm build, focused repository formatting, and diff hygiene passed in secretless fork CI.
  • Fresh automated source review through P2 on c22b1b79cf975dc9335bb45dd19b19ac3e60203a: pass, no findings. The original quadratic lookup finding and later cursor type-narrowing finding are resolved.
  • Not run: full repository test suite, separate full typecheck/lint fan-out, live external channels/providers or browser QA. Upstream required CI remains authoritative for its additional lanes.

AI-assisted implementation and review; the behavior results above were read back from the isolated executions, not inferred from passing unit tests.

@clawsweeper

clawsweeper Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Sep 5, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 5, 2026
@clawsweeper

clawsweeper Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 7, 2026, 9:09 AM ET / 13:09 UTC.

ClawSweeper review

What this changes

Preserves literal final tags in Markdown code examples during reply cleanup, shares that behavior with reasoning cleanup, and adds regression coverage and documentation.

Merge readiness

✅ Ready for maintainer review

This remains a useful, focused fix: current main and v2026.9.2 still contain the reported sanitizer defect. No blocking findings remain, and the prior cursor-narrowing concern is resolved.

Priority: P2
Reviewed head: c22b1b79cf975dc9335bb45dd19b19ac3e60203a

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused owner-level repair with meaningful regression coverage and recorded production CLI proof.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The supplied before/after CLI receipt exercises delivery normalization through sanitizeUserFacingText and stripFinalTags with an isolated OpenClaw runtime and loopback provider, preserving both code examples while stripping outside markers; it proves normalized payload behavior, not Telegram transport.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The supplied before/after CLI receipt exercises delivery normalization through sanitizeUserFacingText and stripFinalTags with an isolated OpenClaw runtime and loopback provider, preserving both code examples while stripping outside markers; it proves normalized payload behavior, not Telegram transport.
Evidence reviewed 9 items Current main still contains the defect: The current-main implementation removes every valid final-tag match without checking Markdown code ownership, so fenced and inline examples lose their literal tags.
Latest release has the same stripping implementation: The inspected v2026.9.2 implementation also strips tags unconditionally; release and fetched main both reference final-tags.ts blob d49f290926f52b0c3aee937295104bc70658bb39.
Shared owner and code-region contract: The patch checks ordered code regions before removing matches. Markdown Core sorts regions by source offset and supplies their start/end boundaries, supporting the advancing cursor without a second parser or configuration surface.
Findings None None.
Security None None.

How this fits together

Reply cleanup turns assistant output into text suitable for delivery. Its shared final-tag helper removes model control markers before CLI results and channel replies reach users.

flowchart TD
  A[Assistant output] --> B[Reply normalization]
  B --> C[User-facing cleanup]
  D[Markdown code regions] --> E[Final-tag cleanup]
  C --> E
  E --> F[Preserve code literals]
  E --> G[Remove outside markers]
  F --> H[Normalized reply]
  G --> H
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +8, Tests +53, Docs +4. Total +65 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 2 22 14 +8
Tests 3 53 0 +53
Docs 1 4 0 +4
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 79 14 +65

Review metrics

Metric Value Why it matters
Production versus regression coverage Production net +8 lines; tests +53; documentation +4 Production growth adds code-region protection and bounded cursor traversal while removing the competing reasoning-cleanup loop.

Technical review

Best possible solution:

Keep code-literal protection in the shared final-tag owner; the small cursor-state increase supports ordered lookup while replacing the duplicate reasoning-cleanup loop.

Do we have a high-confidence way to reproduce the issue?

Yes: current-main source deterministically removes final tags inside inline and fenced code, matching the supplied baseline CLI receipt; this review did not execute a reproduction.

Is this the best way to solve the issue?

Yes: repairing the shared stripping owner aligns final sanitization with existing code-preserving reasoning behavior; a channel-specific workaround would leave other callers broken.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 4bd1d6e305e5.

Labels

Label justifications:

  • P2: Repairs silent alteration of specific XML code examples without changing routing, configuration, or stored state.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The supplied before/after CLI receipt exercises delivery normalization through sanitizeUserFacingText and stripFinalTags with an isolated OpenClaw runtime and loopback provider, preserving both code examples while stripping outside markers; it proves normalized payload behavior, not Telegram transport.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied before/after CLI receipt exercises delivery normalization through sanitizeUserFacingText and stripFinalTags with an isolated OpenClaw runtime and loopback provider, preserving both code examples while stripping outside markers; it proves normalized payload behavior, not Telegram transport.
  • proof: telegram-e2e: This PR needs Telegram Test Server proof with the repository E2E skill. Preserved code-example tags change visible Telegram reply text and are observable through the Telegram Test Server.

Evidence

What I checked:

  • Current main still contains the defect: The current-main implementation removes every valid final-tag match without checking Markdown code ownership, so fenced and inline examples lose their literal tags. (src/shared/text/final-tags.ts:138, 4bd1d6e305e5)
  • Latest release has the same stripping implementation: The inspected v2026.9.2 implementation also strips tags unconditionally; release and fetched main both reference final-tags.ts blob d49f290926f52b0c3aee937295104bc70658bb39. (src/shared/text/final-tags.ts:134, 3928bad9badf)
  • Shared owner and code-region contract: The patch checks ordered code regions before removing matches. Markdown Core sorts regions by source offset and supplies their start/end boundaries, supporting the advancing cursor without a second parser or configuration surface. (packages/markdown-core/src/reasoning-tag-parser.ts:301, c22b1b79cf97)
  • Production entrypoint reaches the repaired helper: Agent command delivery normalizes channel-selected payloads even without sending them. normalizeReplyPayloadOutcome calls sanitizeUserFacingText, whose first filter is stripFinalTags; the CLI JSON therefore exposes the changed production result. This is OpenClaw-owned text processing, with no affirmative dependency on Codex runtime or protocol behavior. (src/agents/command/delivery.ts:546, c22b1b79cf97)
  • Sibling behavior and regression coverage: Reasoning cleanup now delegates to the shared owner while preserving its early return and trim policy. Existing streaming cleanup already protects code using carried parser state. Added tests cover code-region variants, interleaved outside markers, sanitizer composition, and literal-only trimming. (src/shared/text/reasoning-tags.ts:44, c22b1b79cf97)
  • Recorded production CLI proof: The supplied body at sourceRevision 5d95e7f465ab627fc679269c64277fd9f8f263a8a807b9372dadceb109838fd0 records baseline loss and after-fix preservation through the built CLI with an isolated OpenClaw agent and loopback provider. It identifies product head 5654f5f, canonical payloads[].text, observation time 2026-09-05T09:45:33.911Z, and unchanged outside-marker removal. Linked evidence: https://github.com/Alix-007/openclaw/actions/runs/33958481136 . GitHub/API and browser retrieval failed in this reviewer environment, so linked raw logs were not independently inspected; the supplied receipt remains the proof basis. (5654f5f36b2d)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Vincent Koc: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (3 earlier review cycles)
  • reviewed 2026-09-05T09:54:29.979Z sha 5654f5f :: needs maintainer review before merge. :: none
  • reviewed 2026-09-05T10:04:17.230Z sha 5654f5f :: needs changes before merge. :: [P2] Narrow the cursor's code region before dereferencing it
  • reviewed 2026-09-06T02:14:24.633Z sha f155d2b :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 5, 2026
@obviyus obviyus assigned obviyus and unassigned obviyus Sep 5, 2026
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 6, 2026
@shakkernerd shakkernerd self-assigned this Sep 7, 2026
@openclaw-barnacle openclaw-barnacle Bot added the docs Improvements or additions to documentation label Sep 7, 2026
@shakkernerd
shakkernerd merged commit 5bf5dc9 into openclaw:main Sep 7, 2026
214 checks passed
@shakkernerd

Copy link
Copy Markdown
Contributor

Fixed: delivered Markdown code examples retain literal final tags while model final-answer markers outside code are removed.

With thanks to @Alix-007.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 8, 2026
…#138989)

Preserve literal final tags in delivered Markdown code examples while removing model final-answer markers outside code. Document the sanitization boundary and share it with reasoning cleanup.

Refs openclaw#133152.
Reviewed-by: @shakkernerd
Co-authored-by: Shakker <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants