Skip to content

[AI] test(tool-call-repair): add unit tests for grammar and payload modules - #98984

Closed
wangyan2026 wants to merge 2 commits into
openclaw:mainfrom
wangyan2026:test/tool-call-repair-unit-tests
Closed

wangyan2026 wants to merge 2 commits into
openclaw:mainfrom
wangyan2026:test/tool-call-repair-unit-tests

Conversation

@wangyan2026

Copy link
Copy Markdown
Contributor

Summary

Add unit tests for the packages/tool-call-repair/ module covering grammar parsing and payload parsing. The package currently has zero test coverage across all 5 source files. This PR adds comprehensive tests for the two foundational files (grammar.ts and payload.ts) that handle plain-text tool call format recognition, JSON boundary tracking, and tool call block stripping.

  • Problem: packages/tool-call-repair/ (2,299 lines of logic across 5 source files) had zero test coverage
  • Solution: Add 112 unit tests across 2 new test files covering input boundaries, edge cases, and expected behavior for all grammar exports and all public payload exports
  • What changed: 2 new test files only, zero source code changes
  • What did NOT change: No production code, no behavior changes. The promote.ts and stream-normalizer.ts (main state machine) test coverage is deferred to follow-up

Change Type

  • Bug fix
  • Feature
  • Refactor required for the fix
  • Docs
  • Security hardening
  • Chore/infra

Scope

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Motivation

packages/tool-call-repair/ implements the runtime logic for detecting, parsing, and promoting plain-text tool calls emitted by models that do not support native tool calling. The package is consumed by src/shared/, src/plugin-sdk/, src/infra/, and src/agents/ modules, making it a critical dependency. Despite 2,299 lines of parsing logic (state machine, grammar, JSON boundary tracking, promotion), it had zero unit tests. This PR adds coverage for the two pure-logic foundation files that all other modules depend on.

Real behavior proof

  • Behavior addressed: Adding test coverage for previously untested tool-call-repair package files
  • Real environment tested: Linux, Node 24, branch test/tool-call-repair-unit-tests
  • Exact steps or command run after this patch:
pnpm test packages/tool-call-repair/src/grammar.test.ts packages/tool-call-repair/src/payload.test.ts
  • Evidence after fix:
Test Files 2 passed (2) 
     Tests 112 passed (112) 
Start at 14:48:17 
Duration 1.10s
  • Observed result after fix:
  1. grammar.test.ts — 83 tests passing, covering: all 4 grammar constants, matchesLiteralPrefix (exact/prefix/suffix/empty), isPlainTextToolNameChar / isXmlishNameChar character classification, skipHorizontalWhitespace / skipWhitespace (spaces/tabs/newlines), consumeLineBreak (Unix/Windows/standalone CR), findJsonObjectEnd (simple/nested/escaped strings/backslash/empty/unclosed/maxPayloadBytes/offset), skipSerializedToolCallTrailingLineBreak, consumeJsonToolClosingMarker (3 marker formats + leading whitespace), findBracketedJsonPayloadStart (bracket/JSON/missing close/no JSON/CRLF/whitespace), findHarmonyJsonPayloadStart (with/without channel marker/message marker/unknown channel/missing to=/no tool name/missing code/no JSON/commentary/final channels), startsWithAsciiMarkerIgnoreCase (case-insensitive/no match/too short/offset), indexOfAsciiMarkerIgnoreCase (start/offset/not found/available), findXmlishToolCallEnd (XML-ish/bracket/tool: prefix/plain text/no parameters/unclosed/multiple params/case-insensitive/trailing newline)

  2. payload.test.ts — 29 tests passing, covering: parseStandalonePlainTextToolCallBlocks (single/multiple bracket, tool: prefix, harmony with/without channel marker, harmony with message marker, allowedToolNames filter/reject, mixed text rejection, invalid JSON, JSON array rejection, missing/mismatched closing markers, maxPayloadBytes, consecutive tool: calls, CRLF line endings, raw/offset tracking), stripPlainTextToolCallBlocks (bracket-style removal, unchanged text, empty input, start/end removal, multiple blocks, tool: prefix at line start)

  • What was not tested: promote.ts and stream-normalizer.ts (main state machine) — deferred to follow-up PRs. stream-normalizer.ts requires AsyncIterable mocking for the core normalizePlainTextToolCallStreamEvents generator.

User-visible / Behavior Changes

None

Security Impact

  • New permissions/capabilities? No
  • Secrets/tokens handling changed? No
  • New/changed network calls? No
  • Command/tool execution surface changed? No
  • Data access scope changed? No

Compatibility / Migration

  • Backward compatible? Yes
  • Config/env changes? No
  • Migration needed? No

Best-fix Verdict

  • Best fix: Yes — pure test addition is the correct approach; no behavior changes needed
  • Refactor needed: No
  • Alternative considered: Adding tests alongside a behavior change — rejected because these files are stable; tests add regression protection without risking new bugs

AI Assistance 🤖

  • AI-assisted: Yes
  • AI model: deepseek-v4-flash
  • Human confirmed understanding of code changes: Yes

Risks and Mitigations

None — test-only change, zero production code modifications.

…odules

Add 112 unit tests covering:
- grammar.ts: all 12 exports + 4 constants (83 tests)
- payload.ts: parseStandalonePlainTextToolCallBlocks and
  stripPlainTextToolCallBlocks (29 tests)

Tests cover three opening formats (bracket, tool: prefix, harmony),
three closing formats, allowedToolNames filtering, maxPayloadBytes,
JSON boundary cases, line-start detection, and strip behavior.

Related to: test-coverage-improvement
@wangyan2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@clawsweeper

clawsweeper Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 2, 2026, 4:30 AM ET / 08:30 UTC.

Summary
The PR adds Vitest unit tests for packages/tool-call-repair grammar and payload helpers without changing production code.

PR surface: Tests +711. Total +711 across 2 files.

Reproducibility: yes. for the PR defect: the latest check-lint job reports 14 typescript(no-unnecessary-type-assertion) errors in the added payload test file. No current-main product bug is being reproduced because this is test-only cleanup.

Review metrics: 1 noteworthy metric.

  • Lint diagnostics: 14 errors in 1 added test file. These errors are owned by the PR diff and block the required lint check before merge.

Merge readiness
Overall: 🦪 silver shellfish
Proof: 🦪 silver shellfish
Patch quality: 🦪 silver shellfish
Result: blocked until real behavior proof from a real setup is added.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • [P1] Fix the remaining payload.test.ts lint errors.
  • [P1] Add redacted real behavior proof or get a maintainer proof-gate override.

Proof guidance:

  • [P1] Needs real behavior proof before merge: The PR body provides terminal output from unit tests only, which is supplemental test proof rather than after-fix real behavior proof for an external PR. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Risk before merge

  • [P1] Latest CI still fails check-lint because the added payload tests contain unnecessary indexed non-null assertions.
  • [P1] The PR body only shows focused unit-test output; under the external-PR proof gate this is test proof, not after-fix real behavior proof.

Maintainer options:

  1. Decide the mitigation before merge
    Keep the test-only scope, remove the lint-triggering assertions, rerun focused test plus lint validation, and add redacted real behavior proof or get a maintainer proof override before merge.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Next step before merge

  • [P1] Contributor or maintainer handling is needed because the lint repair is small but the external proof gate cannot be satisfied by an automated repair without proof or override.

Security
Cleared: The diff adds Vitest tests only and does not change production code, dependencies, workflows, permissions, lockfiles, network calls, or secret handling.

Review findings

  • [P2] Remove the unnecessary indexed non-null assertions — packages/tool-call-repair/src/payload.test.ts:15-16
Review details

Best possible solution:

Keep the test-only scope, remove the lint-triggering assertions, rerun focused test plus lint validation, and add redacted real behavior proof or get a maintainer proof override before merge.

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

Yes for the PR defect: the latest check-lint job reports 14 typescript(no-unnecessary-type-assertion) errors in the added payload test file. No current-main product bug is being reproduced because this is test-only cleanup.

Is this the best way to solve the issue?

No as submitted. Direct package-level tests are an appropriate layer, but the mergeable version must satisfy existing lint rules and the external-PR proof gate without production-code changes.

Full review comments:

  • [P2] Remove the unnecessary indexed non-null assertions — packages/tool-call-repair/src/payload.test.ts:15-16
    check-lint on the latest PR head reports typescript(no-unnecessary-type-assertion) for the blocks[0]! and blocks[1]! assertions repeated throughout this file. Replace these with a real narrowing or whole-array/object assertions so the added tests can pass required lint.
    Confidence: 0.96

Overall correctness: patch is incorrect
Overall confidence: 0.94

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against f2abf57d32ad.

Label changes

Label justifications:

  • P3: This is low-risk test coverage cleanup with no production behavior change, currently blocked by mechanical lint and proof-gate issues.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦪 silver shellfish.
  • status: 🔁 re-review loop: A fresh ClawSweeper review was explicitly requested after the latest review. Needs real behavior proof before merge: The PR body provides terminal output from unit tests only, which is supplemental test proof rather than after-fix real behavior proof for an external PR. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed

PR surface:

Tests +711. Total +711 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 0 0 0 0
Tests 2 711 0 +711
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 711 0 +711

What I checked:

Likely related people:

  • Vincent Koc: git blame attributes the current grammar.ts and payload.ts package snapshot on main to commit 38442853e104, which is the code these tests exercise. (role: current-line provenance; confidence: medium; commits: 38442853e104; files: packages/tool-call-repair/src/grammar.ts, packages/tool-call-repair/src/payload.ts)
  • steipete: The merged package-introduction PR lists several commits by this author for sharing grammar and extracting the repair package, and GitHub metadata shows they merged that PR. (role: package extraction/refactor author and merger; confidence: high; commits: 5b787c34a039, 4f01d5bd6aae, 3ea911558c45; files: packages/tool-call-repair/src/grammar.ts, packages/tool-call-repair/src/payload.ts, src/plugin-sdk/tool-payload.ts)
  • fuller-stack-dev: They authored the merged PR that introduced the serialized tool-call repair package and surrounding behavior, making them relevant for behavior-level routing. (role: merged feature PR author; confidence: medium; commits: e64271f1bb4b; files: packages/tool-call-repair/src/grammar.ts, packages/tool-call-repair/src/payload.ts, packages/tool-call-repair/src/stream-normalizer.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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.

How this review workflow works
  • 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.

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. labels Jul 2, 2026
- grammar.test.ts: remove unused functionOpen, rename params_ to p
- payload.test.ts: replace result! assertions with local const blocks = result!

Related to: openclaw#98984
@wangyan2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

I've fixed the lint issues and pushed the changes. Please re-review.

@clawsweeper

clawsweeper Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@steipete

Copy link
Copy Markdown
Contributor

Superseded by #104100, landed as 05ebaf41f6ee71729149ff83bf8c3ff8a37261a8.

The landed canonical scanner refactor includes and expands this proposed grammar/payload coverage as part of a 315-test focused matrix, alongside stream-normalizer, provider payload, and agent-path regressions. Exact-head CI and live gateway proof are recorded on #104100. Thanks @ZOOWH for identifying and covering this gap.

@steipete steipete closed this Jul 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: L status: 🔁 re-review loop A fresh ClawSweeper review was explicitly requested after the latest review.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants