Skip to content

Add JsonReadHelpers and WslShellQuoting canonical helpers (additive) - #994

Merged
bkudiess merged 1 commit into
mainfrom
bkudiess-json-read-helpers-and-wsl-quoting
Jul 16, 2026
Merged

bkudiess merged 1 commit into
mainfrom
bkudiess-json-read-helpers-and-wsl-quoting

Conversation

@bkudiess

Copy link
Copy Markdown
Collaborator

Summary

Additive PR 2 of the architecture refactor. It establishes two canonical, single-source helpers that were previously copy-pasted across the codebase, with thorough tests and ledger updates.

  • JsonReadHelpers (src/OpenClaw.Shared/JsonReadHelpers.cs, internal static) — the canonical home for the non-nullable, fallback-returning family of JsonElement coercion helpers: GetString, TryGetString, GetInt/GetLong/GetDouble, GetArrayLength, FirstNonEmpty. All accessors are total (never throw) — a missing property, JSON null, wrong JsonValueKind, or non-object parent yields the documented fallback, folding in the defensive GetStringSafe non-object guard.
  • WslShellQuoting (src/OpenClaw.Shared/WslShellQuoting.cs, internal static) — POSIX/WSL single-quote quoting using the '\'' idiom, kept deliberately separate from the cmd.exe/PowerShell ShellQuoting (which doubles single quotes — wrong and injection-unsafe for WSL command lines). Two distinct operations: EscapePosixSingleQuoteInner (escape-only) and QuotePosixSingleQuote (fully-wrapped token).
  • Proof-of-adoption routing: OpenClawGatewayClient.ParseUsageCost now uses JsonReadHelpers.GetInt (3 sites); the duplicate private GetInt is removed. Behavior-identical — those payloads are always JSON objects.
  • Ledger (docs/ARCHITECTURE.md): json-read-helpers and wsl-posix-quoting moved planned → authoritative with real behavioral guard tests; single-source-owners table and the SetupSteps "extract-toward" guidance updated.

PR 2 is additive only. The SetupSteps.cs POSIX-quoting call-site migration is intentionally deferred to PR 3. (SetupSteps currently has two same-named ShellEscape methods with divergent wrap semantics — exactly the divergence WslShellQuoting retires.)

Scope of the canonical contract (intentionally narrow)

JsonReadHelpers canonicalizes the non-nullable fallback-returning family only. It is not a drop-in for every private JSON helper — several existing helpers have deliberately different contracts and must not be blindly routed through it (each needs a call-site guard or a dedicated variant). This is documented in the type's XML doc and the ledger residue:

  • Models.GetInt/GetLong return int?/long? (null sentinel = missing); Models.GetLong has no double→long fallback (canonical truncates instead).
  • WorkspaceFilesModel.GetLong rejects negatives (>= 0); canonical accepts negatives.
  • WindowsNodeClient.TryGetString treats empty/whitespace as absent; canonical returns true for "" (present).
  • Mxc.MxcAvailability.FirstNonEmpty trims; SetupSteps.FirstNonEmpty trims + returns "no output"; canonical is verbatim / null.
  • Some older getters throw on a non-object parent; canonical is total.

Validation

$env:OPENCLAW_REPO_ROOT=(Get-Location).Path set for all runs (linked worktree).

Command Result
.\build.ps1 ✅ all 5 projects, warning-clean (TreatWarningsAsErrors=true)
dotnet test .\tests\OpenClaw.Shared.Tests\OpenClaw.Shared.Tests.csproj ✅ 2863 passed, 0 failed, 31 skipped
dotnet test .\tests\OpenClaw.Tray.Tests\OpenClaw.Tray.Tests.csproj ✅ 1717 passed, 0 failed

ArchitectureLedgerConsistencyTests (ledger format + guard-test existence) and GatewayProtocolDriftTests (unaffected by the routing) are green.

Real behavior proof

Proof profile: pure helper. No UI/MCP/node-capability/gateway surface is touched, so the proof is the automated unit tests that directly exercise the changed behavior:

  • JsonReadHelpersTests — missing property, JSON null, wrong kind, valid string/number, empty-string-vs-null, empty array, int64 clamp to int range, fractional→long truncation, fallback params, non-object parent, and FirstNonEmpty selection/verbatim/whitespace/null-array.
  • WslShellQuotingTests — empty→'', whitespace, embedded/single/multiple quotes, newlines, multi-line fragments, $(...), backticks, URLs, JSON arrays, Windows backslash paths, already-quoted input, a quote-breakout payload (x'; rm -rf / #), the escape-only-vs-wrapped invariant, the no-bare-unescaped-quote invariant, and a guard asserting divergence from PowerShell quoting.

Rubber-duck review

Adversarial dual-model review (GPT-5.5 + Claude Opus 4.8) was run on the diff, and the coordinator independently ran a second dual-model pass:

  • No blocking findings. Both passes confirmed the GetInt routing is behavior-identical, WslShellQuoting is POSIX-correct/injection-safe, the hand-computed '\'' test expectations are correct, and the ledger is well-formed with existing guard tests.
  • Hardening applied: the canonical FirstNonEmpty would NullReferenceException on a single bare null argument (latent, unreachable today, matched the pre-existing helpers) → added a values is null guard + regression test.
  • Contract-narrowing resolution (consensus): the docs/ledger no longer claim the helper is the "union of all private helpers"; the authoritative scope is narrowed to the non-nullable fallback-returning family, with the divergent variants (null-sentinel / non-negative / whitespace-absent / trimming) explicitly listed as separate and not-to-be-blindly-migrated.
  • Nullable-flow fix: TryGetString's out param now carries [NotNullWhen(true)].
  • Doc accuracy fix: GetInt's XML doc clarifies that numbers within long range but beyond int are clamped, while numbers beyond long range return the fallback (behavior unchanged from the deleted private helper).

Additive PR 2 of the architecture refactor. Introduces two single-source
helpers previously copy-pasted across the codebase, with thorough tests and
ledger updates. No runtime behavior change beyond one behavior-identical
call-site routing.

- JsonReadHelpers: canonical, total (never-throwing) JsonElement coercion for
  the non-nullable, fallback-returning helper family (GetString, TryGetString,
  GetInt/GetLong/GetDouble, GetArrayLength, FirstNonEmpty). Docs explicitly
  scope out the divergent null-sentinel / non-negative / whitespace-absent /
  trimming variants that must not be blindly migrated.
- WslShellQuoting: POSIX/WSL single-quote quoting (the '\'' idiom), deliberately
  separate from the cmd/PowerShell ShellQuoting. Escape-only and fully-wrapped
  are two distinct operations.
- OpenClawGatewayClient.ParseUsageCost: route 3 GetInt sites to
  JsonReadHelpers.GetInt; remove the duplicate private GetInt.
- docs/ARCHITECTURE.md: move json-read-helpers and wsl-posix-quoting from
  planned to authoritative with behavioral guard tests; narrow the ledger
  scope to the non-nullable fallback family.

Co-authored-by: Copilot App <[email protected]>
@bkudiess bkudiess changed the title PR 2: Add JsonReadHelpers and WslShellQuoting canonical helpers (additive) Add JsonReadHelpers and WslShellQuoting canonical helpers (additive) Jul 15, 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. P3 Low-risk cleanup, docs, polish, ergonomics, or speculative feature. labels Jul 16, 2026
@clawsweeper

clawsweeper Bot commented Jul 16, 2026

Copy link
Copy Markdown

Codex review: needs maintainer review before merge. Reviewed July 16, 2026, 12:01 AM ET / 04:01 UTC.

Summary
Adds canonical JSON coercion and POSIX/WSL quoting helpers, routes three gateway usage-cost reads through the JSON helper, and adds focused tests plus architecture-ledger ownership entries.

Reproducibility: not applicable. This PR is an additive internal refactor rather than a report of broken existing behavior.

Review metrics: 4 noteworthy metrics.

  • Patch surface: 6 files changed; 736 additions, 17 deletions. The change is predominantly isolated helper implementation and regression coverage rather than broad runtime churn.
  • Canonical helpers: 2 added. The PR establishes one JSON-reading owner and one POSIX/WSL quoting owner with deliberately separate contracts.
  • Runtime adoption: 3 call sites changed, 1 duplicate removed. Only gateway usage-cost integer parsing changes in production code, keeping the initial adoption boundary narrow.
  • Focused coverage: 2 test files added, 484 test lines. Both helper contracts receive extensive edge-case and injection-oriented regression coverage.

Merge readiness
Overall: 🐚 platinum hermit
Proof: 🐚 platinum hermit
Patch quality: 🐚 platinum hermit
Result: ready for maintainer review.

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

Rank-up moves:

  • none.

Next step before merge

  • No automated repair is indicated; the clean collaborator PR needs ordinary maintainer review and merge handling rather than a separate fix lane.

Security
Cleared: No concrete security or supply-chain concern was found; the patch adds internal parsing and quoting code without changing dependencies, workflows, permissions, secrets, or artifact sources.

Review details

Best possible solution:

Land the focused canonical-helper extraction after normal maintainer review, then migrate SetupSteps quoting separately with real WSL command proof that distinguishes escape-only text from fully wrapped shell tokens.

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

Not applicable; this PR is an additive internal refactor rather than a report of broken existing behavior.

Is this the best way to solve the issue?

Yes; narrowly scoped canonical helpers with explicit documentation of incompatible legacy variants avoid unsafe bulk migration while establishing testable ownership seams.

AGENTS.md: found and applied where relevant.

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

Label changes

Label changes:

  • add P3: This is low-risk internal architecture cleanup with a narrow behavior-preserving production adoption.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The collaborator-authored patch is a pure internal helper extraction with no directly observable UI, MCP, node-command, or gateway workflow change; focused tests and green CI are appropriate evidence here.

Label justifications:

  • P3: This is low-risk internal architecture cleanup with a narrow behavior-preserving production adoption.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The collaborator-authored patch is a pure internal helper extraction with no directly observable UI, MCP, node-command, or gateway workflow change; focused tests and green CI are appropriate evidence here.
Evidence reviewed

What I checked:

  • Current main still lacks the extraction: At current main, the architecture ledger describes JSON coercion and POSIX/WSL quoting as planned owners rather than authoritative helpers, so the PR remains necessary. (docs/ARCHITECTURE.md:55, bf0fa8a9bde4)
  • Existing implementation remains duplicated on main: The current gateway client retains its private integer JSON reader; the PR replaces its three usage-cost call sites with the canonical helper and removes that duplicate. (src/OpenClaw.Shared/OpenClawGatewayClient.cs:3837, bf0fa8a9bde4)
  • Focused implementation commit: The single PR commit introduces two internal helpers, narrowly adopts one helper, and supplies dedicated regression coverage without dependency, workflow, or persisted-data changes. (src/OpenClaw.Shared/JsonReadHelpers.cs:1, d24a6dd634ec)
  • Repository validation is green: The supplied GitHub context reports successful Windows builds, tests, E2E setup checks, repository hygiene, CodeQL, and language analysis on the PR head. (d24a6dd634ec)
  • Architecture policy alignment: The patch updates the ownership ledger in the same change as the extraction and adds behavioral guard tests for both newly authoritative seams, matching repository architecture guidance. (docs/ARCHITECTURE.md:55, d24a6dd634ec)

Likely related people:

  • shanselman: Recent repository history repeatedly connects this person with gateway-facing and shared-client changes near the affected runtime surface. (role: recent shared and gateway area contributor; confidence: medium; files: src/OpenClaw.Shared/OpenClawGatewayClient.cs)
  • AlexAlves87: Recent merged repository work places this person near shared Windows-node implementation and validation surfaces, making them a secondary routing candidate. (role: adjacent shared-code contributor; confidence: low; files: src/OpenClaw.Shared)
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.

@bkudiess
bkudiess merged commit e0afbc4 into main Jul 16, 2026
19 checks passed
@bkudiess
bkudiess deleted the bkudiess-json-read-helpers-and-wsl-quoting branch July 16, 2026 18:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P3 Low-risk cleanup, docs, polish, ergonomics, or speculative feature. 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.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant