Repository navigation
fix(cli): name PowerShell when it strips quotes from JSON flags - #17351
Conversation
Greptile SummaryThe PR improves diagnostics for JSON flags damaged by Windows PowerShell 5.1 while preserving non-JSON orchestration flag contracts.
Confidence Score: 5/5The PR appears safe to merge. No blocking failure remains.
|
| Filename | Overview |
|---|---|
| src/cli/flags.ts | Adds a JSON-specific optional flag accessor while leaving opaque string flags on their existing accessor. |
| src/cli/quote-stripped-json-flag.ts | Implements narrow quote-stripping detection and emits a sanitized diagnostic without exposing the supplied value. |
| src/cli/handlers/orchestration/gate-handlers.ts | Applies quote-stripping diagnostics to gate options that are parsed downstream as a JSON string array. |
| src/cli/handlers/orchestration/message-payload.ts | Applies quote-stripping diagnostics to structured message payloads. |
| src/main/runtime/orchestration/db/generated-id.ts | Centralizes the generated ID byte length and exposes validation tied to the generator’s exact shape. |
| src/main/runtime/orchestration/task-deps-flag.ts | Reuses the shared generated-ID validator for safe PowerShell dependency recovery. |
| src/main/git/worktree-scan-cache.ts | Adds separately keyed strict scan coalescing so strict failures cannot be softened by lenient callers. |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart LR
A[CLI JSON-valued flag] --> B{Valid JSON?}
B -->|Yes| C[Pass value downstream]
B -->|No| D{Matches quote-stripped shape?}
D -->|Yes| E[Report PowerShell 5.1 guidance]
D -->|No| C
Reviews (3): Last reviewed commit: "fix(cli): scope JSON-flag detection to g..." | Re-trigger Greptile
| @@ -104,7 +104,7 @@ export const ORCHESTRATION_TASK_HANDLERS: Record<string, CommandHandler> = { | |||
| { | |||
| id: getRequiredStringFlag(flags, 'id'), | |||
| status, | |||
| result: getOptionalStringFlag(flags, 'result'), | |||
| result: getOptionalJsonFlag(flags, 'result'), | |||
There was a problem hiding this comment.
JSON validation rejects plain strings
When --result contains a bracketed bare-token string such as [ok], getOptionalJsonFlag rejects it even though the runtime stores results as opaque strings. The same validation also rejects bracketed orchestration ask --options values even though that runtime path parses options by splitting on commas, preventing previously accepted requests before RPC dispatch.
📝 WalkthroughWalkthroughThe CLI adds JSON-aware flag handling for orchestration options and payloads, including quote-stripping diagnostics. Generated task ID validation now uses a shared exact-format validator. Worktree scan sharing now separates strict Git failures from fail-soft results while preserving coalescing for matching scan modes. Tests cover all three changes. Merge Risk: 🔵 Low · up to The CLI now detects likely PowerShell 5.1 quote stripping for JSON flags, but object inputs with normal whitespace around separators can bypass the targeted diagnostic and still show a generic parse error. This is a bounded, non-blocking usability gap that should remain under owner awareness or follow-up. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description explains the problem, rationale, implementation, scope, and verification, but it omits several required template sections. It has no required Linked Issue entry, Visual Proof or explicit N/A statement, AI Disclosure, Review, Agent skill upstream boundary, Notes, or Checklist content. Resolution Add the required template sections and complete them. Include a
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: cc6b72af-be23-4cc2-8bf8-fa609d321c7f
📥 Commits
Reviewing files that changed from the base of the PR and between 252dbd6 and 3ebd18b4d80980073c6bbed4a40bb355f28d9283.
📒 Files selected for processing (10)
src/cli/flags.tssrc/cli/handlers/orchestration/gate-handlers.tssrc/cli/handlers/orchestration/message-payload.tssrc/cli/handlers/orchestration/question-handler.tssrc/cli/handlers/orchestration/task-handlers.tssrc/cli/quote-stripped-json-flag.test.tssrc/cli/quote-stripped-json-flag.tssrc/main/runtime/orchestration/db/generated-id.tssrc/main/runtime/orchestration/task-deps-flag.test.tssrc/main/runtime/orchestration/task-deps-flag.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review.
| const mangled = describeQuoteStrippedJsonFlag(name, value) | ||
| if (mangled) { | ||
| throw new RuntimeClientError('invalid_argument', mangled) |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win
Sensitive Data Exposure (CWE-200): Exposure of Sensitive Information to an Unauthorized Actor
Reachability: External · Exploitability: Moderate
Reachability path
● Entry
src/cli/handlers/orchestration/message-payload.ts:4
getOptionalStructuredMessagePayload: Why: raw JSON args are fragile in Windows PowerShell; these flags avoid shell-specific quoting.
│
▼
● Sink
src/cli/flags.ts
Redact the raw JSON value from the diagnostic.
describeQuoteStrippedJsonFlag includes raw.trim() in the RuntimeClientError message. A secret-bearing JSON flag can therefore appear in human or --json error output. Preserve the PowerShell guidance, but replace the raw value with a safe placeholder or omit it.
There was a problem hiding this comment.
Important
Two of the four flags wired to getOptionalJsonFlag are not actually JSON-valued: ask --options is a comma-separated CSV (not an array), and --result is stored verbatim as the task's failure string rather than parsed as JSON. The JSON/PowerShell-specific detection and error text don't fit those two flags.
Reviewed changes
- Quote-stripped detection — new
src/cli/quote-stripped-json-flag.tswithlooksQuoteStripped(bracketed, no inner quotes,JSON.parsefails, every comma token is a bare token) anddescribeQuoteStrippedJsonFlag. getOptionalJsonFlaghelper —src/cli/flags.tsthrowsRuntimeClientError('invalid_argument', …)when the damaged shape is detected.- Flag wiring —
--options(gate-create + ask),--payload(send),--result(task-update) moved fromgetOptionalStringFlagtogetOptionalJsonFlag. - Shared ID contract —
GENERATED_ID_BYTES+isGeneratedIdingenerated-id.tsreplace the hardcoded/^task_[0-9a-f]{12}$/iintask-deps-flag.ts, with a test pinning the validator to the generator.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
|
Thanks — three of these were real, and two of them were bugs I introduced. All fixed in
That leaves the detector on only the two flags that are genuinely JSON-parsed: Objects needed a Raw value echoed in the error — fixed. A Shell attribution was unconditional — fixed. Detection inspects only the value's shape, so it also fires when a macOS/Linux user forgets to quote. The message now reads "If you ran this from Windows PowerShell 5.1…" rather than asserting it. VerificationRe-ran all six cases against a Windows host with the rebuilt CLI:
Secret redaction checked on the host too:
One note on the earlier CI failure
|
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: cc98957e-47e0-412e-b543-7efcc77c31f1
📥 Commits
Reviewing files that changed from the base of the PR and between 3ebd18b4d80980073c6bbed4a40bb355f28d9283 and ccffe9d321621806d30f707e704a707b55d0b2b1.
📒 Files selected for processing (5)
src/cli/quote-stripped-json-flag.test.tssrc/cli/quote-stripped-json-flag.tssrc/main/git/worktree-scan-cache-sharing.test.tssrc/main/git/worktree-scan-cache.tssrc/main/git/worktree.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.
| */ | ||
|
|
||
| const BARE_TOKEN = /^[A-Za-z0-9_.:+-]+$/ | ||
| const BARE_OBJECT_ENTRY = /^([A-Za-z0-9_.+-]+):([A-Za-z0-9_.+-]+)$/ |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Allow JSON whitespace around object separators.
When quote stripping changes {"a": "b"} to {a: b}, BARE_OBJECT_ENTRY rejects the entry because the regex allows no whitespace around :. looksQuoteStripped then returns false, so the targeted workaround is not shown.
Allow JSON whitespace around the separator and add regressions for {a: b} and {a : b}.
Proposed fix
-const BARE_OBJECT_ENTRY = /^([A-Za-z0-9_.+-]+):([A-Za-z0-9_.+-]+)$/
+const BARE_OBJECT_ENTRY = /^([A-Za-z0-9_.+-]+)[ \t\r\n]*:[ \t\r\n]*([A-Za-z0-9_.+-]+)$/📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const BARE_OBJECT_ENTRY = /^([A-Za-z0-9_.+-]+):([A-Za-z0-9_.+-]+)$/ | |
| const BARE_OBJECT_ENTRY = /^([A-Za-z0-9_.+-]+)[ \t\r\n]*:[ \t\r\n]*([A-Za-z0-9_.+-]+)$/ |
There was a problem hiding this comment.
Important
One scope concern below — the PowerShell JSON-flag fix itself looks correct, but the second commit bundles an unrelated worktree-scan-cache refactor.
Reviewed changes
- Reverted
orchestration ask --optionsandorchestration task-update --resultback togetOptionalStringFlag, leaving onlygate-create --optionsandsend --payloadongetOptionalJsonFlag. - Tightened
looksQuoteStrippedso an object is only reported when every entry is a barekey:valuepair ({a,b}is now left alone). - Made the error secret-safe by not echoing the raw value, and hedged the PowerShell attribution behind "If you ran this from Windows PowerShell 5.1".
- Refactored
src/main/git/worktree-scan-cache.tsinto a sharedshareWorktreeScanhelper, adding an exportedlistWorktreesSharedStrictand three new tests.
⚠️ Unrelated worktree-scan-cache refactor bundled into a CLI fix commit
Commit ccffe9d3 ("scope JSON-flag detection to genuinely JSON flags") also rewrites worktree-scan-cache.ts — extracting shareWorktreeScan and exporting listWorktreesSharedStrict, which has no production callers. This is not mentioned in the commit message or the PR description, and it is dead exported API. Split it into its own PR or drop it from this one; it should not ride along unannounced in a PowerShell CLI fix.
Technical details
# Unrelated worktree refactor in ccffe9d3
## Affected sites
- src/main/git/worktree-scan-cache.ts:57 — new `shareWorktreeScan(repoPath, options, run)` helper
- src/main/git/worktree-scan-cache.ts:100 — new exported `listWorktreesSharedStrict`, no production callers
- src/main/git/worktree.ts:26 — re-export of `listWorktreesSharedStrict`
- src/main/git/worktree-scan-cache-sharing.test.ts — three tests for the new export
## Required outcome
- Either remove the worktree-scan-cache changes from this PR, or move them to a separate PR whose description explains the intended caller.
## Open questions for the human (optional)
- Is `listWorktreesSharedStrict` a preview of worktree-create verification (#16520)? If it stays, consider an explicit discriminator argument instead of `run.name`, which couples cache-key correctness to the JS engine's `Function.name` semantics.DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Windows PowerShell 5.1 does not escape inner quotes when building a native command line, so `--options '["a","b"]'` reaches orca.exe as `--options [a,b]`. The value is correct when printed and damaged by the time argv is parsed, so the resulting "invalid JSON" error blamed the user's input rather than the shell. #16743 recovered this for `--deps`, which is safe only because generated task IDs have a fixed 12-hex grammar. The same mangling hits `--options`, `--payload` and `--result`, and those are NOT safely recoverable: `["1","2"]` and `[1,2]` arrive at argv identically, so a general repair would silently turn strings into numbers. Detect instead. `getOptionalJsonFlag` rejects the damaged shape up front with an error that names the shell and shows the workaround. It fires only when the value is bracketed, quote-free, fails JSON.parse, AND consists entirely of bare tokens that quoting would rescue, so valid JSON is untouched. Also share the generated-id contract: `task-deps-flag` hardcoded /^task_[0-9a-f]{12}$/i, which silently diverges if `generateId`'s byte count changes. It now calls `isGeneratedId`, with a test pinning the two together. Verified on a Windows host. Measured argv, which the new test pins as a fixture: PS_VALUE=["task_b2a580db74d8","task_c3b691ec85e9"] ARGV=["--deps","[task_b2a580db74d8,task_c3b691ec85e9]"] Before: Invalid --options: must be a JSON array of strings After: --options arrived as [a,b], which is not valid JSON. Windows PowerShell 5.1 strips the inner quotes ...
Review found the detector wired to two flags that are not JSON:
- `orchestration ask --options` is documented `<csv>` and the runtime splits it
on commas, so `--options [a,b]` was a legitimate value being rejected.
- `task-update --result` is stored verbatim and reused as dispatch failure text;
existing tests pass free text, so a bracketed `[ok]` was being rejected.
Both revert to `getOptionalStringFlag`. Only `gate-create --options`
(`<json_array>`) and `send --payload` (`<json>`) are JSON-parsed and keep it.
Three further review fixes:
- Objects now require a `key:value` pair per entry. `{a,b}` and `{a:b,c}` were
reported as quote-stripped although quoting them cannot produce valid JSON.
- The raw value is no longer echoed. A `--payload` can carry secrets and this
message reaches `--json` output; the flag name and guidance are enough.
- The message hedges the shell attribution. Detection inspects only the value's
shape, so it also fires when a macOS/Linux user forgets to quote, where
PowerShell is not involved.
Verified against a Windows host, all six cases: both JSON flags fire on the
mangled shape and pass valid JSON through to the runtime; both non-JSON flags
now reach the runtime again; and the secret in `{token:hunter2}` appears zero
times in the error output.
ccffe9d to
e9b435e
Compare
…lyai#17351) * fix(cli): name PowerShell when it strips quotes from JSON flags Windows PowerShell 5.1 does not escape inner quotes when building a native command line, so `--options '["a","b"]'` reaches orca.exe as `--options [a,b]`. The value is correct when printed and damaged by the time argv is parsed, so the resulting "invalid JSON" error blamed the user's input rather than the shell. stablyai#16743 recovered this for `--deps`, which is safe only because generated task IDs have a fixed 12-hex grammar. The same mangling hits `--options`, `--payload` and `--result`, and those are NOT safely recoverable: `["1","2"]` and `[1,2]` arrive at argv identically, so a general repair would silently turn strings into numbers. Detect instead. `getOptionalJsonFlag` rejects the damaged shape up front with an error that names the shell and shows the workaround. It fires only when the value is bracketed, quote-free, fails JSON.parse, AND consists entirely of bare tokens that quoting would rescue, so valid JSON is untouched. Also share the generated-id contract: `task-deps-flag` hardcoded /^task_[0-9a-f]{12}$/i, which silently diverges if `generateId`'s byte count changes. It now calls `isGeneratedId`, with a test pinning the two together. Verified on a Windows host. Measured argv, which the new test pins as a fixture: PS_VALUE=["task_b2a580db74d8","task_c3b691ec85e9"] ARGV=["--deps","[task_b2a580db74d8,task_c3b691ec85e9]"] Before: Invalid --options: must be a JSON array of strings After: --options arrived as [a,b], which is not valid JSON. Windows PowerShell 5.1 strips the inner quotes ... * fix(cli): scope JSON-flag detection to genuinely JSON flags Review found the detector wired to two flags that are not JSON: - `orchestration ask --options` is documented `<csv>` and the runtime splits it on commas, so `--options [a,b]` was a legitimate value being rejected. - `task-update --result` is stored verbatim and reused as dispatch failure text; existing tests pass free text, so a bracketed `[ok]` was being rejected. Both revert to `getOptionalStringFlag`. Only `gate-create --options` (`<json_array>`) and `send --payload` (`<json>`) are JSON-parsed and keep it. Three further review fixes: - Objects now require a `key:value` pair per entry. `{a,b}` and `{a:b,c}` were reported as quote-stripped although quoting them cannot produce valid JSON. - The raw value is no longer echoed. A `--payload` can carry secrets and this message reaches `--json` output; the flag name and guidance are enough. - The message hedges the shell attribution. Detection inspects only the value's shape, so it also fires when a macOS/Linux user forgets to quote, where PowerShell is not involved. Verified against a Windows host, all six cases: both JSON flags fire on the mangled shape and pass valid JSON through to the runtime; both non-JSON flags now reach the runtime again; and the secret in `{token:hunter2}` appears zero times in the error output.

Problem
Windows PowerShell 5.1 does not escape inner quotes when it builds a native command line. A correct value is mangled between the shell and
orca.exe:(measured on a real Windows host, not inferred — this value is now a test fixture)
The value is correct when printed and damaged by the time argv is parsed, so the resulting "invalid JSON" error pointed at the user's input rather than at the shell that broke it.
Why not just recover, like #16743 did
#16743 recovers this shape for
--deps. That is safe only because generated task IDs have a fixedtask_[0-9a-f]{12}grammar.The same mangling hits
--options,--payloadand--result, and those are not safely recoverable —["1","2"]and[1,2]arrive at argv identically, so a general repair would silently turn strings into numbers. Guessing is worse than failing here.So this detects and reports instead of repairing. The
--depsrecovery is untouched.Change
getOptionalJsonFlag(insrc/cli/flags.ts) rejects the damaged shape up front, naming the shell and giving the workaround. Wired into the four JSON-valued orchestration flags:--options(gate-create, ask),--payload(send),--result(task-update).Detection is deliberately narrow — it fires only when the value is bracketed, contains no quotes, fails
JSON.parse, and consists entirely of bare tokens that quoting would rescue. Valid JSON, non-JSON text, and values quoting would not fix are all left alone.Also included:
task-deps-flaghardcoded/^task_[0-9a-f]{12}$/i, duplicating the contract ingenerateId(randomBytes(6)). Change the generator's byte count and that validator silently stops matching with no test failing. It now calls a sharedisGeneratedId, with a test pinning the two together.Verification
Against a live Windows host:
--options [a,b]Invalid --options: must be a JSON array of strings$vworkaround--options ["a","b"]pnpm tcclean;src/cli+src/main/runtime/orchestrationsuites green;oxlintclean.Negative control on the shared ID contract: drift
generateIdto 8 bytes and the new guard fails, which is exactly the silent breakage it exists to catch.Scope
Detection only. It does not change what any host accepts, adds no wire surface, and is inert on macOS/Linux, where the shell escapes correctly and the flag never reaches the damaged shape.