Skip to content

CLI: complete positional args in zsh completion - #69305

Closed
sk7n4k3d wants to merge 3 commits into
openclaw:mainfrom
sk7n4k3d:fix/zsh-completion-positional-args
Closed

sk7n4k3d wants to merge 3 commits into
openclaw:mainfrom
sk7n4k3d:fix/zsh-completion-positional-args

Conversation

@sk7n4k3d

Copy link
Copy Markdown
Contributor

Summary

  • Problem: `openclaw wiki ingest `, `openclaw wiki scan `, and every other leaf command with a positional argument emits a zsh completion function that lists options only. Typing `openclaw wiki ingest T` triggers the terminal bell instead of completing filenames, reported in [Bug]: zsh completion for openclaw wiki ingest does not complete file paths #69293.
  • Why it matters: leaf commands with a ``/``/`<files...>` argument are the ones shell completion actually helps with. Today the generated zsh function skips that slot entirely.
  • What changed: `generateZshArgs` still renders option flags; a new `generateZshPositionalArgs` walks `cmd.registeredArguments` and emits one `"::"` per argument, using `_files` when the argument name hints at a path/file/source/etc., `_files -/` for dir/folder hints, and a neutral action otherwise. Variadic trailing args (`[tags...]`) emit position `*`. Only leaf command blocks consume the new helper so the existing subcommand dispatch (`_values 'command'`) on non-leaf commands is unchanged.
  • What did NOT change (scope boundary): bash / fish / powershell generators, option flag rendering, argument-less leaf commands, subcommand dispatch, `completion-runtime`, `completion-fish` helpers.

Change Type (select all)

  • Bug fix

Scope (select all touched areas)

  • UI / DX

Linked Issue/PR

Root Cause (if applicable)

  • Root cause: `generateZshArgs` only iterated `cmd.options`. The leaf-command template in `generateZshSubcommands` called `_arguments -C` with just those option specs, so Commander `.argument("", ...)` declarations were never exported to zsh.
  • Missing detection / guardrail: the existing completion-cli tests exercised option flag rendering and compinit deferral, but never asserted that a positional argument reaches the generated function.
  • Contributing context: Commander 14 exposes `registeredArguments` on every `Command`; earlier completion work used only `cmd.options`.

Regression Test Plan (if applicable)

  • Coverage level that should have caught this:
    • Unit test
  • Target test or file: `src/cli/completion-cli.test.ts`
  • Scenario the test should lock in: for a leaf command declared with `.argument("", "Local file path to ingest")`, the generated zsh script must contain `"1:Local file path to ingest:_files"`. Equivalent assertions cover `` (`_files -/`) and variadic `[tags...]` (`*:` position).
  • Why this is the smallest reliable guardrail: a single string-containment check against the emitted script deterministically detects the regression without needing a live zsh process.
  • Existing test that already covers this (if any): none.

User-visible / Behavior Changes

`openclaw completion --shell zsh` now emits positional argument specs for every leaf command. After sourcing the generated script, `` on `openclaw wiki ingest`, `openclaw wiki doctor` (etc.) completes filesystem paths just like any other zsh file argument. No other shells are touched.

Diagram (if applicable)

```text
Before:
openclaw wiki ingest T -> terminal bell, no completion

After:
openclaw wiki ingest T -> Tone.md Topic.md ... (zsh _files)
```

Security Impact (required)

  • 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

Repro + Verification

Environment

  • OS: Linux (Arch CachyOS); fix is shell-side, reproducer in the issue is macOS.
  • Runtime/container: pnpm workspace, Node 22, vitest.
  • Model/provider: N/A
  • Integration/channel (if any): N/A
  • Relevant config: none

Steps

  1. Build the program with a leaf command declaring `.argument("", "Local file path to ingest")` (done in `createCompletionProgram` in the test file).
  2. Call `getCompletionScript("zsh", program)`.
  3. Assert the generated function `_openclaw_wiki_ingest` includes `"1:Local file path to ingest:_files"`.

Expected

  • Generated zsh function contains positional spec `"1::_files"` (or `_files -/` for dir hints, `*` position for variadic).

Actual (before this change)

  • Generated zsh function contained only option specs; no positional slot, so zsh file completion never fired on the argument.

Evidence

  • Failing test/log before + passing after

New unit tests (3 scenarios: file hint, dir hint, variadic) fail on `main`, pass on this branch. Local commands run:

```
pnpm test src/cli/completion-cli.test.ts

7 passed (4 pre-existing + 3 new)

pnpm lint src/cli/completion-cli.ts src/cli/completion-cli.test.ts

0 warnings, 0 errors

pnpm tsgo && pnpm tsgo:core:test

clean

```

Manual inspection of the generated script for a `wiki ingest` command produces exactly the shape the issue reporter asked for:

```
_openclaw_wiki_ingest() {
_arguments -C \
"--title[Title]" \
"--json[JSON]" \
"1:Local file path to ingest:_files"
}
```

Human Verification (required)

  • Verified scenarios:
    • File-hint argument (``) emits `_files`.
    • Directory-hint argument (``) emits `_files -/`.
    • Variadic trailing argument (`[tags...]`) emits position `*` with the argument description.
    • Non-hint argument (``) emits a neutral action so zsh does not over-complete with file names.
    • Option flag rendering is byte-identical (pre-existing test `generates zsh functions for nested subcommands` still passes unchanged).
  • Edge cases checked:
    • Argument description is zsh-escaped (backslashes, quotes, colons, brackets) via `escapeZshLabel`.
    • Intermediate commands (`wiki`) continue to render subcommand dispatch; `generateZshPositionalArgs` only runs on the leaf-command branch.
    • Commander 14 exposes `registeredArguments`; fallback to `_args` kept for resilience.
  • What you did not verify:
    • Live zsh `compinit` expansion was not run on this workstation (zsh not installed); the existing `defers zsh registration until compinit is available` test gates that on CI.
    • Bash / fish / powershell generators — intentionally out of scope for this PR.

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

Compatibility / Migration

  • Backward compatible? Yes (generated script is a strict superset of the previous one for leaf commands; users who re-run `openclaw completion --shell zsh --write-state` pick up the new specs).
  • Config/env changes? No
  • Migration needed? No

Risks and Mitigations

  • Risk: a positional argument with a file-like name but no filesystem semantics would wrongly suggest files.
    • Mitigation: the hint regex is narrow (path/file/files/source/target/src/dest/destination/dir/directory/folder with word boundaries); any other name defaults to a neutral action, not `_files`.

This PR is AI-assisted (Claude). Degree of testing: fully tested via new unit tests plus scoped `pnpm lint` / `pnpm tsgo` / `pnpm tsgo:core:test`. I read the generated output end-to-end and verified it matches the shape the issue reporter requested.

@openclaw-barnacle openclaw-barnacle Bot added cli CLI command changes size: S labels Apr 20, 2026
@greptile-apps

greptile-apps Bot commented Apr 20, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a missing positional argument completion in the generated zsh completion script. A new generateZshPositionalArgs helper walks cmd.registeredArguments and emits position:label:action specs using _files / _files -/ based on argument name heuristics, and generateZshLeafArgs combines these with the existing option specs. Three new unit tests cover file-hint, dir-hint, and variadic cases. The scope is strictly limited to the zsh generator for leaf commands, and the existing subcommand dispatch is unchanged.

Confidence Score: 5/5

Safe to merge; remaining findings are cosmetic P2 issues that don't affect correct completion behaviour for realistic descriptions.

The bug fix logic is correct, tests cover the three main scenarios, and the change is well-scoped. Both open findings are P2: one is a single-quote escaping mismatch that only manifests when a CLI arg description literally contains a single quote (very rare), and the other is a trivial regex redundancy.

No files require special attention.

Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/cli/completion-cli.ts
Line: 224-229

Comment:
**Single-quote escaping wrong for double-quoted zsh context**

`escapeZshLabel` applies the `'\''` pattern (which is for exiting and re-entering single-quoted shell strings) but the output is always embedded inside a double-quoted zsh spec like `"1:label:action"`. Inside zsh `"..."`, a single quote is already a literal character — no escaping is needed. As a result, a description like `"don't use this"` would produce `"1:don'\''t use this:_files"`, and zsh would display the label as `don\''t use this` rather than `don't use this`.

The fix is to simply not escape single quotes here (they're harmless inside double-quoted strings):

```suggestion
function escapeZshLabel(value: string): string {
  return value
    .replace(/\\/g, "\\\\")
    .replace(/"/g, '\\"')
    .replace(/:/g, "\\:")
    .replace(/\[/g, "\\[")
    .replace(/\]/g, "\\]");
}
```

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: src/cli/completion-cli.ts
Line: 209

Comment:
**Redundant `files` in `FILE_ARG_HINT` alternation**

`file` followed by the `s?` quantifier already matches `files`, so listing `files` explicitly in the alternation is redundant. Consider removing it to keep the regex concise:

```suggestion
const FILE_ARG_HINT = /(^|[_-])(path|file|source|target|src|dest|destination)s?($|[_-])/i;
```

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "CLI: complete positional args in zsh com..." | Re-trigger Greptile

Comment thread src/cli/completion-cli.ts Resolved
Comment thread src/cli/completion-cli.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7fede4549a

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/cli/completion-cli.ts Resolved
@sk7n4k3d

Copy link
Copy Markdown
Contributor Author

Thanks for the review — pushed a971ee3b addressing all three P2 comments:

  1. Optional positional semantics (Codex): generateZshPositionalArgs now honors Argument.required and emits n::MESSAGE:ACTION / *::MESSAGE:ACTION for Commander's [name] / [name...] forms, so completion no longer misrepresents optional arguments as required. Added a dedicated test ([term] → "1::Optional search term: "); the variadic test's expected spec was updated from *: to *:: since [tags...] is optional.
  2. escapeZshLabel (Greptile): dropped the single-quote '\'' substitution — labels are always embedded inside double-quoted zsh specs, so single quotes pass through literally.
  3. FILE_ARG_HINT (Greptile): removed the redundant files alternation; file + s? already covers it.

pnpm test src/cli/completion-cli.test.ts → 8/8 green. pnpm lint, pnpm tsgo:core, pnpm tsgo:core:test all clean.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a971ee3b3d

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/cli/completion-cli.ts Resolved
@prtags

prtags Bot commented Apr 23, 2026

Copy link
Copy Markdown

Related work from PRtags group pretty-bear-eteg

Title: Open PR duplicate: [Bug]: zsh completion for openclaw wiki ingest does not complete file paths

Number Title
#69305* CLI: complete positional args in zsh completion
#69352 fix: complete zsh positional wiki ingest paths
#69509 fix(cli): add positional argument completion for zsh leaf commands

* This PR

@vincentkoc
vincentkoc force-pushed the fix/zsh-completion-positional-args branch from a971ee3 to 65e847b Compare April 28, 2026 07:43
@vincentkoc

Copy link
Copy Markdown
Member

ProjectClownfish pushed a narrow repair to this branch so the original contributor path can stay canonical.

Source PR: #69305
Validation: pnpm -s vitest run src/cli/completion-cli.test.ts; pnpm check:changed
Contributor credit is preserved in the branch history and PR context.

@clawsweeper

clawsweeper Bot commented Apr 28, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the context here. I swept through the related work, and this is now duplicate or superseded.

Keep open. Current main still omits zsh positional specs for leaf commands, and this PR remains the canonical fix path for the linked zsh completion bug, but the branch is not merge-ready because the new positional-label path still leaves shell substitution characters active, the branch is conflicting, it lacks real zsh proof, and it edits release-owned CHANGELOG.md.

Root-cause cluster
Relationship: canonical
Canonical: #69305
Summary: This PR is the active canonical implementation candidate for the missing zsh positional completion bug; two similar PR attempts are closed unmerged, and the adjacent escaping PR covers only part of the same zsh completion surface.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Canonical path: Close this stale PR. The latest review rated it F, the branch still lacks merge-ready proof, and there has been no human follow-up after the durable review.

So I’m closing this here because the remaining work is already tracked in the canonical issue.

Review details

Best possible solution:

Close this stale PR. The latest review rated it F, the branch still lacks merge-ready proof, and there has been no human follow-up after the durable review.

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

Yes, from source inspection rather than a live zsh run: current main's leaf zsh template only emits option specs, while wiki ingest declares a positional file argument. That is enough to reproduce the missing generated spec path in the code.

Is this the best way to solve the issue?

Mostly yes on owner boundary: the generic zsh completion generator is the right place, not a memory-wiki workaround. The current branch is not the best mergeable form until it hardens label escaping, drops the changelog edit, refreshes conflicts, and adds live zsh proof.

Security review:

Security review needs attention: The new positional zsh label path emits sourced shell-code strings without escaping shell substitution characters.

  • [medium] Unescaped shell substitution in zsh positional labels — src/cli/completion-cli.ts:224
    Descriptions are embedded in double-quoted zsh specs, so $, $(), and backticks can be expanded by the shell rather than displayed literally when completion runs.
    Confidence: 0.87

AGENTS.md: found and applied where relevant.

What I checked:

  • stale F-rated PR: PR was opened 2026-04-20T11:10:08Z, is older than 60 days, and the latest review rated it F.
  • proof blocker: real behavior proof is missing and proof tier is F, so this branch is not merge-ready without contributor follow-up.
  • no human follow-up: live comments and timeline hydrated by apply contain no non-automation activity after the ClawSweeper review.

Likely related people:

  • steipete: Recent commit history for src/cli/completion-cli.ts includes generated-completion hardening and several CLI completion follow-ups. (role: recent area contributor; confidence: high; commits: 308af8599171, 6ce9e0dd9b65, f427ddc220b5; files: src/cli/completion-cli.ts, src/cli/completion-cli.test.ts)
  • vincentkoc: Recent CLI history includes completion-adjacent fixes, and this PR branch also contains a narrow maintainer repair commit from this person. (role: recent adjacent contributor; confidence: medium; commits: fdddb413ef26, 65e847b40754; files: src/cli/completion-cli.ts, src/cli/completion-cli.test.ts)
  • hydro13: The zsh completion registration behavior and its zsh integration test were introduced in the current completion module history. (role: zsh completion contributor; confidence: medium; commits: 6be14ab388eb; files: src/cli/completion-cli.ts, src/cli/completion-cli.test.ts)
  • yiShanXin: Earlier completion generator work covered generated shell scripts and nested completion behavior in the same module. (role: completion generator contributor; confidence: medium; commits: bbb0c3e5d7d9; files: src/cli/completion-cli.ts, src/cli/completion-cli.test.ts)

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

@vincentkoc vincentkoc added clawsweeper Tracked by ClawSweeper automation and removed clownfish:human-review labels Apr 28, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. labels May 20, 2026
@clawsweeper

clawsweeper Bot commented May 20, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper PR egg

🎁 Pass real behavior proof to wake the egg and unlock a hatchable treat.

Where did the egg go?
  • The egg game starts only after the PR passes the real-behavior proof check.
  • Before that, no creature or rarity is rolled. The treat waits for real proof.
  • This is still just collectible flavor: proof affects review readiness, not creature quality.

@openclaw-barnacle openclaw-barnacle Bot added the triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. label May 20, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Jun 6, 2026
@clawsweeper clawsweeper Bot added rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jun 6, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Jun 7, 2026
@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. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Jun 14, 2026
@clawsweeper

clawsweeper Bot commented Jun 19, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper applied the proposed close for this PR.

@clawsweeper clawsweeper Bot closed this Jun 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

clawsweeper Tracked by ClawSweeper automation cli CLI command changes merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: S status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: zsh completion for openclaw wiki ingest does not complete file paths

2 participants