Skip to content

Commit d24a6dd

Browse files
bkudiessCopilot
andcommitted
Add JsonReadHelpers and WslShellQuoting canonical helpers (PR 2)
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]>
1 parent bf0fa8a commit d24a6dd

6 files changed

Lines changed: 736 additions & 17 deletions

File tree

‎docs/ARCHITECTURE.md‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,8 @@ These are the canonical homes. Do not reintroduce private copies elsewhere.
5252
| Loopback MCP server for tests | `OpenClaw.TestSupport.FakeMcpServer` | authoritative |
5353
| Gateway record test data | `OpenClaw.Connection.Tests.GatewayRecordBuilder` | authoritative |
5454
| Settings test data | `OpenClaw.TestSupport.SettingsDataBuilder` | authoritative |
55-
| JSON `JsonElement` coercion | `JsonReadHelpers` (planned) | planned |
56-
| WSL/POSIX shell quoting | dedicated POSIX quote APIs (planned) | planned |
55+
| JSON `JsonElement` coercion (non-nullable fallback family) | `JsonReadHelpers` | authoritative |
56+
| WSL/POSIX shell quoting | `WslShellQuoting` | authoritative |
5757
| Capability UI metadata | `NodeCapabilityUiCatalog` (planned) | planned |
5858
| Capability registration/gating | `NodeCapabilityRegistrationPolicy` (planned) | planned |
5959
| Local MCP exposure policy | `McpCapabilityPolicy` (planned) | planned |
@@ -74,7 +74,7 @@ These are the canonical homes. Do not reintroduce private copies elsewhere.
7474
| `src/OpenClaw.Shared/Models.cs` | per-domain model files + `*Mapper` classes |
7575
| `src/OpenClaw.Shared/Capabilities/SystemCapability.cs` | `ExecApprovalService` |
7676
| `src/OpenClaw.Connection/GatewayConnectionManager.cs` | `NodeConnectionCoordinator`, `BootstrapTokenLifecycle`, `DevicePairApprovalCoordinator` |
77-
| `src/OpenClaw.SetupEngine/SetupSteps.cs` | one file per step; `WslShellClient`, `GatewayConfigScriptBuilder`, `KeepaliveProcessManager` |
77+
| `src/OpenClaw.SetupEngine/SetupSteps.cs` | one file per step; `WslShellClient`, `WslShellQuoting`, `GatewayConfigScriptBuilder`, `KeepaliveProcessManager` |
7878
| Any test hand-rolling a temp dir / env save-restore / CLI capture | `OpenClaw.TestSupport` fixtures |
7979

8080
## Ledger
@@ -107,8 +107,8 @@ leading and trailing pipe. Columns, in order:
107107
| test-fake-mcp | authoritative | OpenClaw.WinNode.Cli.Tests | private internal FakeMcpServer copy | OpenClaw.TestSupport.FakeMcpServer | - | one loopback MCP server captures method/body/auth and returns canned/timeout responses | TestSupportFixtureTests.FakeMcpServer_CapturesRequest | behavioral | when all MCP-round-trip tests share it |
108108
| test-gateway-builder | authoritative | OpenClaw.Connection.Tests | per-file MakeRecord(id,url) helpers | OpenClaw.Connection.Tests.GatewayRecordBuilder | pre-existing MakeRecord until migrated | gateway record test data has one builder | TestSupportFixtureTests.GatewayRecordBuilder_BuildsRecord | behavioral | when MakeRecord helpers are removed |
109109
| test-settings-builder | authoritative | scattered test files | ad hoc SettingsData construction in migrated tests | OpenClaw.TestSupport.SettingsDataBuilder | pre-existing un-migrated tests until adopted | settings test data starts from production defaults | TestSupportFixtureTests.SettingsDataBuilder_StartsFromDefaults | behavioral | when settings tests adopt the builder |
110-
| json-read-helpers | planned | OpenClaw.Shared (multiple files) | duplicate private GetString/TryGetString/FirstNonEmpty helpers | JsonReadHelpers | - | one JSON coercion helper with defined null/wrong-kind behavior | none | review-only | extracted in PR 2 |
111-
| wsl-posix-quoting | planned | OpenClaw.SetupEngine/SetupSteps.cs | ad hoc ShellEscape with divergent wrap semantics | dedicated POSIX quote APIs | - | WSL scripts use POSIX quoting, never cmd/PowerShell quoting | none | review-only | extracted in PR 2-3 |
110+
| json-read-helpers | authoritative | OpenClaw.Shared (multiple files) | duplicate non-nullable fallback-returning JsonElement getters | JsonReadHelpers | null-sentinel / non-negative / whitespace-absent / trimming variants stay separate | canonical non-nullable fallback JSON coercion; divergent-contract helpers are not blindly routed here | JsonReadHelpersTests.GetString_ReturnsNull_WhenPropertyMissing | behavioral | when the non-nullable fallback getters are all routed here |
111+
| wsl-posix-quoting | authoritative | OpenClaw.SetupEngine/SetupSteps.cs | ad hoc ShellEscape with divergent wrap semantics | WslShellQuoting | SetupSteps ShellEscape until PR 3 migration | WSL scripts use POSIX quoting not cmd/PowerShell quoting | WslShellQuotingTests.QuotePosixSingleQuote_WrapsAndEscapesEmbeddedQuote | behavioral | when SetupSteps call sites use WslShellQuoting |
112112
| app-window-manager | planned | src/OpenClaw.Tray.WinUI/App.xaml.cs | window creation/show/hide/shutdown | IWindowManager | composition/delegation only | startup/shutdown ordering deterministic; disposed once | none | review-only | extracted in Phase 3 |
113113
| app-tray-controller | planned | src/OpenClaw.Tray.WinUI/App.xaml.cs | tray icon/menu/action routing | ITrayController | composition/delegation only | tray actions route unchanged | none | review-only | extracted in Phase 3 |
114114
| app-activation-router | planned | src/OpenClaw.Tray.WinUI/App.xaml.cs | deep-link/toast/single-instance activation | IActivationRouter | composition/delegation only | activation routes land on the same UI/actions; current-user pipe security preserved | none | review-only | extracted in Phase 3 |
Lines changed: 188 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,188 @@
1+
using System.Diagnostics.CodeAnalysis;
2+
using System.Text.Json;
3+
4+
namespace OpenClaw.Shared;
5+
6+
/// <summary>
7+
/// Canonical home for the <em>non-nullable, fallback-returning</em> family of
8+
/// <see cref="JsonElement"/> coercion helpers: the gateway-client-style getters
9+
/// (<c>GetString</c> returning <c>null</c> when absent, numeric getters returning
10+
/// a caller-supplied fallback, <c>GetArrayLength</c>, and a verbatim
11+
/// <c>FirstNonEmpty</c>) plus the defensive non-object guard that the
12+
/// <c>GetStringSafe</c> variant added. See docs/ARCHITECTURE.md →
13+
/// <c>json-read-helpers</c>.
14+
///
15+
/// All accessors are <em>total</em> (they never throw): a missing property, a
16+
/// JSON null, a value of the wrong <see cref="JsonValueKind"/>, or a non-object
17+
/// <paramref name="parent"/> yields the documented fallback (<c>null</c> / 0 /
18+
/// the caller-supplied fallback) rather than an exception — including a non-object
19+
/// element, which <see cref="JsonElement.TryGetProperty(string, out JsonElement)"/>
20+
/// would otherwise throw on.
21+
///
22+
/// <para><b>Scope — do not blindly migrate.</b> This is deliberately NOT a
23+
/// drop-in for every private JSON helper in the repo. Several existing helpers
24+
/// have different contracts; routing them through these methods changes behavior
25+
/// and needs a call-site guard or a dedicated variant:</para>
26+
/// <list type="bullet">
27+
/// <item><c>Models.GetInt</c> / <c>Models.GetLong</c> return <c>int?</c> /
28+
/// <c>long?</c> (a null sentinel means "missing"), and <c>Models.GetLong</c> has
29+
/// no double-to-long fallback — the canonical <see cref="GetLong"/> instead
30+
/// truncates a fractional number.</item>
31+
/// <item><c>WorkspaceFilesModel.GetLong</c> rejects negatives (requires
32+
/// <c>&gt;= 0</c>); the canonical getters accept negative numbers.</item>
33+
/// <item><c>WindowsNodeClient.TryGetString</c> treats empty/whitespace as
34+
/// <em>absent</em>; the canonical <see cref="TryGetString"/> returns <c>true</c>
35+
/// with an empty string ("" is present).</item>
36+
/// <item><c>Mxc.MxcAvailability.FirstNonEmpty</c> trims its result, and
37+
/// <c>SetupSteps.FirstNonEmpty</c> trims and falls back to <c>"no output"</c>;
38+
/// the canonical <see cref="FirstNonEmpty"/> returns the first value verbatim, or
39+
/// <c>null</c>.</item>
40+
/// <item>Some older getters throw on a non-object <paramref name="parent"/>
41+
/// (failing the parse); the canonical getters are total and return the fallback.</item>
42+
/// </list>
43+
/// </summary>
44+
internal static class JsonReadHelpers
45+
{
46+
/// <summary>
47+
/// Returns the string value of <paramref name="property"/>, or <c>null</c>
48+
/// when <paramref name="parent"/> is not an object, the property is absent, or
49+
/// the value is not a JSON string. The returned string may be empty; only
50+
/// missing / non-string values collapse to <c>null</c>.
51+
/// </summary>
52+
internal static string? GetString(JsonElement parent, string property)
53+
{
54+
if (parent.ValueKind != JsonValueKind.Object
55+
|| !parent.TryGetProperty(property, out var value)
56+
|| value.ValueKind != JsonValueKind.String)
57+
{
58+
return null;
59+
}
60+
61+
return value.GetString();
62+
}
63+
64+
/// <summary>
65+
/// Try-pattern companion to <see cref="GetString"/>. Returns <c>true</c> and
66+
/// sets <paramref name="value"/> when the property exists and is a JSON string
67+
/// (the string may be empty); otherwise returns <c>false</c> with
68+
/// <paramref name="value"/> set to <c>null</c>.
69+
/// </summary>
70+
internal static bool TryGetString(JsonElement parent, string property, [NotNullWhen(true)] out string? value)
71+
{
72+
value = GetString(parent, property);
73+
return value is not null;
74+
}
75+
76+
/// <summary>
77+
/// Returns the <see cref="int"/> value of <paramref name="property"/>, or
78+
/// <paramref name="fallback"/> when it is missing or not a JSON number. A
79+
/// number within <see cref="long"/> range that exceeds the <see cref="int"/>
80+
/// range is clamped to the <see cref="int"/> range; a number beyond
81+
/// <see cref="long"/> range returns <paramref name="fallback"/> (matching the
82+
/// prior private helper).
83+
/// </summary>
84+
internal static int GetInt(JsonElement parent, string property, int fallback = 0)
85+
{
86+
if (parent.ValueKind != JsonValueKind.Object
87+
|| !parent.TryGetProperty(property, out var value)
88+
|| value.ValueKind != JsonValueKind.Number)
89+
{
90+
return fallback;
91+
}
92+
93+
if (value.TryGetInt32(out var intValue))
94+
{
95+
return intValue;
96+
}
97+
98+
if (value.TryGetInt64(out var longValue))
99+
{
100+
return (int)Math.Clamp(longValue, int.MinValue, int.MaxValue);
101+
}
102+
103+
return fallback;
104+
}
105+
106+
/// <summary>
107+
/// Returns the <see cref="long"/> value of <paramref name="property"/>, or
108+
/// <paramref name="fallback"/> when it is missing or not a JSON number. A
109+
/// fractional number is truncated toward zero.
110+
/// </summary>
111+
internal static long GetLong(JsonElement parent, string property, long fallback = 0)
112+
{
113+
if (parent.ValueKind != JsonValueKind.Object
114+
|| !parent.TryGetProperty(property, out var value)
115+
|| value.ValueKind != JsonValueKind.Number)
116+
{
117+
return fallback;
118+
}
119+
120+
if (value.TryGetInt64(out var longValue))
121+
{
122+
return longValue;
123+
}
124+
125+
if (value.TryGetDouble(out var doubleValue))
126+
{
127+
return (long)doubleValue;
128+
}
129+
130+
return fallback;
131+
}
132+
133+
/// <summary>
134+
/// Returns the <see cref="double"/> value of <paramref name="property"/>, or
135+
/// <paramref name="fallback"/> when it is missing or not a JSON number.
136+
/// </summary>
137+
internal static double GetDouble(JsonElement parent, string property, double fallback = 0)
138+
{
139+
if (parent.ValueKind != JsonValueKind.Object
140+
|| !parent.TryGetProperty(property, out var value)
141+
|| value.ValueKind != JsonValueKind.Number)
142+
{
143+
return fallback;
144+
}
145+
146+
return value.TryGetDouble(out var doubleValue) ? doubleValue : fallback;
147+
}
148+
149+
/// <summary>
150+
/// Returns the number of elements in the array at <paramref name="property"/>,
151+
/// or 0 when it is missing or not a JSON array.
152+
/// </summary>
153+
internal static int GetArrayLength(JsonElement parent, string property)
154+
{
155+
if (parent.ValueKind != JsonValueKind.Object
156+
|| !parent.TryGetProperty(property, out var value)
157+
|| value.ValueKind != JsonValueKind.Array)
158+
{
159+
return 0;
160+
}
161+
162+
return value.GetArrayLength();
163+
}
164+
165+
/// <summary>
166+
/// Returns the first value that is not <c>null</c>, empty, or whitespace, or
167+
/// <c>null</c> when none qualify. Values are returned verbatim (not trimmed).
168+
/// </summary>
169+
internal static string? FirstNonEmpty(params string?[] values)
170+
{
171+
// A bare `null` argument binds to the params array itself rather than a
172+
// one-element array; guard so the canonical helper never throws.
173+
if (values is null)
174+
{
175+
return null;
176+
}
177+
178+
foreach (var value in values)
179+
{
180+
if (!string.IsNullOrWhiteSpace(value))
181+
{
182+
return value;
183+
}
184+
}
185+
186+
return null;
187+
}
188+
}

‎src/OpenClaw.Shared/OpenClawGatewayClient.cs‎

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3837,7 +3837,7 @@ private void ParseUsageCost(JsonElement payload)
38373837
var summary = new GatewayCostUsageInfo
38383838
{
38393839
UpdatedAt = ParseUnixTimestampMs(payload, "updatedAt") ?? DateTime.UtcNow,
3840-
Days = GetInt(payload, "days")
3840+
Days = JsonReadHelpers.GetInt(payload, "days")
38413841
};
38423842

38433843
if (payload.TryGetProperty("totals", out var totals) && totals.ValueKind == JsonValueKind.Object)
@@ -3850,7 +3850,7 @@ private void ParseUsageCost(JsonElement payload)
38503850
CacheWrite = GetLong(totals, "cacheWrite"),
38513851
TotalTokens = GetLong(totals, "totalTokens"),
38523852
TotalCost = GetDouble(totals, "totalCost"),
3853-
MissingCostEntries = GetInt(totals, "missingCostEntries")
3853+
MissingCostEntries = JsonReadHelpers.GetInt(totals, "missingCostEntries")
38543854
};
38553855
}
38563856

@@ -3867,7 +3867,7 @@ private void ParseUsageCost(JsonElement payload)
38673867
CacheWrite = GetLong(day, "cacheWrite"),
38683868
TotalTokens = GetLong(day, "totalTokens"),
38693869
TotalCost = GetDouble(day, "totalCost"),
3870-
MissingCostEntries = GetInt(day, "missingCostEntries")
3870+
MissingCostEntries = JsonReadHelpers.GetInt(day, "missingCostEntries")
38713871
});
38723872
}
38733873
}
@@ -4038,15 +4038,6 @@ private static string BuildProviderSummary(GatewayUsageStatusInfo status)
40384038
};
40394039
}
40404040

4041-
private static int GetInt(JsonElement parent, string property)
4042-
{
4043-
if (!parent.TryGetProperty(property, out var value) || value.ValueKind != JsonValueKind.Number)
4044-
return 0;
4045-
if (value.TryGetInt32(out var intVal)) return intVal;
4046-
if (value.TryGetInt64(out var longVal)) return (int)Math.Clamp(longVal, int.MinValue, int.MaxValue);
4047-
return 0;
4048-
}
4049-
40504041
private static long GetLong(JsonElement parent, string property)
40514042
{
40524043
if (!parent.TryGetProperty(property, out var value) || value.ValueKind != JsonValueKind.Number)
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
namespace OpenClaw.Shared;
2+
3+
/// <summary>
4+
/// POSIX / WSL single-quote quoting. This is a deliberately separate contract
5+
/// from <see cref="ShellQuoting"/>, which targets Windows cmd.exe / PowerShell
6+
/// (double quotes, or single quotes doubled as <c>''</c>). Those rules are
7+
/// <em>wrong and injection-unsafe</em> for the bash/sh command lines OpenClaw
8+
/// builds to run inside WSL.
9+
///
10+
/// A POSIX shell performs no processing whatsoever inside single quotes — there
11+
/// is no backslash escape for a single quote. The only way to place a literal
12+
/// single quote in a single-quoted string is to close the quote, emit an escaped
13+
/// literal quote, then reopen: the canonical <c>'\''</c> idiom. Every embedded
14+
/// single quote is replaced by that four-character sequence.
15+
///
16+
/// The two operations are kept distinct on purpose (see docs/ARCHITECTURE.md →
17+
/// <c>wsl-posix-quoting</c>); conflating "escape the inner text" with "produce a
18+
/// wrapped token" is exactly the divergent-semantics bug this type retires:
19+
/// <list type="bullet">
20+
/// <item><see cref="EscapePosixSingleQuoteInner"/> escapes embedded quotes for a
21+
/// value the caller is placing between its <em>own</em> outer single quotes, and
22+
/// adds no quotes of its own.</item>
23+
/// <item><see cref="QuotePosixSingleQuote"/> returns a complete, standalone
24+
/// single-quoted token (<c>''</c> for an empty value).</item>
25+
/// </list>
26+
/// Neither operation trims, collapses, or otherwise interprets the input: the
27+
/// bytes between the quotes are preserved verbatim, which is what makes the
28+
/// result injection-safe for arbitrary values (URLs, JSON, paths, newlines).
29+
/// </summary>
30+
internal static class WslShellQuoting
31+
{
32+
// Close quote ('), an escaped literal quote (\'), then reopen quote (').
33+
private const string EscapedSingleQuote = "'\\''";
34+
35+
/// <summary>
36+
/// Escapes embedded single quotes using the POSIX <c>'\''</c> idiom, for a
37+
/// value the caller will wrap in its own outer single quotes. Does NOT add
38+
/// outer quotes. An empty input yields an empty string.
39+
/// </summary>
40+
internal static string EscapePosixSingleQuoteInner(string value)
41+
{
42+
ArgumentNullException.ThrowIfNull(value);
43+
return value.Replace("'", EscapedSingleQuote);
44+
}
45+
46+
/// <summary>
47+
/// Wraps <paramref name="value"/> in single quotes, escaping any embedded
48+
/// single quotes, so the result is exactly one POSIX-shell token. An empty
49+
/// input yields <c>''</c> (an empty argument, not an omitted one).
50+
/// </summary>
51+
internal static string QuotePosixSingleQuote(string value)
52+
{
53+
ArgumentNullException.ThrowIfNull(value);
54+
return string.Concat("'", EscapePosixSingleQuoteInner(value), "'");
55+
}
56+
}

0 commit comments

Comments
 (0)