### Launch PSCompletions interactive menu Source: https://github.com/abgox/pscompletions/blob/main/README.md Starts the PSCompletions interactive menu by running the psc command. ```shell psc ``` -------------------------------- ### Install PSCompletions via install script for bash/zsh/fish Source: https://github.com/abgox/pscompletions/blob/main/README.md Runs the official install script for bash, zsh, or fish shells using curl. The script will also provide loading instructions after installation. ```shell curl -fsSL https://raw.githubusercontent.com/abgox/PSCompletions/main/install.sh | sh ``` -------------------------------- ### psc add — install completions Source: https://github.com/abgox/pscompletions/blob/main/design/psc-cli.md Installs named completions, downloading the remote index and each completion's files concurrently. Always reinstalls, resetting customizations. Errors: no args → 'Too few parameters.', unknown name → ': is not an available completion.', download failure → 'error: '. With --json, output includes data.completions with one result per name; plain text prints ': Added.'. ```text psc add ... ``` -------------------------------- ### psc info command usage Source: https://github.com/abgox/pscompletions/blob/main/design/psc-cli.md Shows the CLI syntax for the `info` subcommand, listing all installed completions or per-name metadata. The no-arg form lists all installed completions with full metadata. ```bash psc info # list all installed completions psc info ... # per-name metadata ``` -------------------------------- ### psc add ... Source: https://github.com/abgox/pscompletions/blob/main/design/psc-cli.md Installs one or more named completions. Downloads the remote index, installs each completion, and refreshes settings. Reinstalls existing completions, resetting customizations. ```APIDOC ## [CLI] psc add ... ### Description Installs one or more named completions. Downloads the remote index, then installs each named completion. Multiple completions download concurrently (8 workers) and each completion's files download in parallel. Each installed completion: files are copied into `completions//`, `.update` records the remote version, and settings are refreshed. `add` always reinstalls: the whole per-completion entry is dropped and rebuilt from remote defaults (customizations are reset). An already-installed name is reinstalled without error and still reports `Added.`. ### Method CLI command ### Endpoint `psc add ...` ### Parameters #### Arguments - **name** (string) - Required - One or more completion names to install. ### Options - `--json` - Output results in JSON format. ### Output - **JSON**: `data.completions` carries one result per name — `{name, ok, error?}`. - **Plain text**: `: Added.` for each successful name. ### Errors - No args → `Too few parameters.` - Unknown name → `: is not an available completion.` - Download failure → `error: ` - A downloaded `config.json` without a usable `id` is refused — nothing lands, the installed version stays intact. - A failed item fails the run: exit code `1`. ### PS Wrapper Forwards with `--json`, then `init_data()` and renders the rich `info.add.done` / `info.update.done` template per added completion. ``` -------------------------------- ### Install PSCompletions via Scoop Source: https://github.com/abgox/pscompletions/blob/main/README.md Installs PSCompletions using the Scoop package manager. The commented alternative abyss/abgox.PSCompletions is shown as an option. ```shell scoop install pscompletions # scoop install abyss/abgox.PSCompletions ``` -------------------------------- ### Concrete example: git help traversal Source: https://github.com/abgox/pscompletions/blob/main/authoring/collecting-info.md Shows how to run `--help` for git and its subcommands to collect options. The first line of each subcommand's help is typically the description and should be used as the `tip` value. ```powershell git --help # top-level commands: add, commit, push, ... git add --help # options for `add` git commit --help # options for `commit` (it has no sub-subcommands) git push --help # options for `push` ``` -------------------------------- ### psc update usage examples Source: https://github.com/abgox/pscompletions/blob/main/design/psc-cli.md Shows the main forms of the `update` command: real-time check with no arguments, named updates, `--old` for out-of-date completions, and `--all` for every installed completion. Always downloads the index first; symlinked completions are skipped. ```bash psc update # real-time library check, no write psc update ... # update named completions (naming = intent to update) psc update --old # update every out-of-date completion psc update --all # update every installed completion ``` -------------------------------- ### Install PSCompletions module in PowerShell Source: https://github.com/abgox/pscompletions/blob/main/README.md Installs the PSCompletions module from the PowerShell Gallery. The commented alternative Install-PSResource PSCompletions is shown as an option. ```powershell Install-Module PSCompletions # Install-PSResource PSCompletions ``` -------------------------------- ### pyenv install usage block with multiple invocation shapes Source: https://github.com/abgox/pscompletions/blob/main/authoring/collecting-info.md Shows a Usage block listing several invocation shapes, one per line. Each indented line starting with the command word is a separate usage shape, not a wrap of the first; record each as its own usage and never let one leak into the description. ```text Usage: pyenv install [-f] [-kvp] [:]... pyenv install [-f] [-kvp] [:] pyenv install -l|--list [--bare] ``` -------------------------------- ### Add git completions with psc add Source: https://github.com/abgox/pscompletions/blob/main/README.md Adds completions for the git command using the psc add subcommand. ```shell psc add git ``` -------------------------------- ### psc.on hook examples with command, option, multiple, and spec arrays Source: https://github.com/abgox/pscompletions/blob/main/design/hooks.md Shows declarative psc.on hooks: single command, multiple=true for repeated slots, wildcard command segments, option chains, spec arrays, and root context. The contract explains slot gating, option suffix matching, and multiple behavior. ```lua psc.on({ command = "exec" }, function() psc.add({ name = "mybin", repeat_count = 99 }) end) ``` ```lua -- multiple: the location's slot keeps matching after it has been filled — -- `git rebase ` and `git rebase xxx ` (selected or typed) both fire. psc.on({ command = "rebase", multiple = true }, function() psc.add({ name = "yyy" }) end) ``` ```lua -- the same switch where the command takes any number of names: after -- `apt install a`, the next Tab must still list packages. psc.on({ command = "install", multiple = true }, add_available) ``` ```lua psc.on({ command = { "", "set" } }, function() -- "" wildcards any segment at that position psc.add({ name = "value" }) end) ``` ```lua psc.on({ option = "--arch" }, function() psc.add({ name = "x86_64" }) end) ``` ```lua -- Option CHAIN: suffix of the completed option sequence (contiguous, in order; -- option values never enter the sequence; `""` wildcards a segment). Not anchored -- at a root — the option sequence has no root. psc.on({ command = "branch", option = { "--move", "--copy" } }, function() psc.add({ name = "both" }) end) ``` ```lua -- Spec ARRAY: elements are ORed; each element follows the single-spec rules. psc.on({ { command = "config" }, { command = "install", option = "--arch" }, }, function() psc.add({ name = "hit" }) end) ``` ```lua psc.on({}, function() -- root psc.add({ name = "bin" }) end) ``` -------------------------------- ### config.json manifest example Source: https://github.com/abgox/pscompletions/blob/main/authoring/manifest.md Shows the required and optional fields of a completion manifest. `id` is a random UUID generated at creation, `version` is the CLI version the completion was checked against, and `language` corresponds to files in the `language/` directory. `hooks` and `alias` are optional; omit `hooks` when there is no `hooks.lua`. ```jsonc { "id": "", "version": "git 2.56.0", // "hooks": true, // "alias": [...], "language": ["en-US", "zh-CN"] } ``` -------------------------------- ### Per-completion config JSON example Source: https://github.com/abgox/pscompletions/blob/main/authoring/manifest.md Shows the structure of the manifest's `config` field: an array of entries with `name`, `value`, optional `values`, and `tip`. The engine merges global config, these defaults, and the user's override (`psc completion `), with later layers overriding earlier. A `name` starting with `enable` or `disable` is machine-constrained to `value` 0/1 and `values` exactly `[0, 1]`. ```json { "config": [ { "name": "max_commit", "value": 30, "values": [-1, 30], "tip": [ "The maximum number of commits the hook parses. Default to 30.", "Use -1 to parse all commits, which slows loading." ] } ] } ``` -------------------------------- ### psc config command usage Source: https://github.com/abgox/pscompletions/blob/main/design/psc-cli.md Shows the CLI syntax for the `config` subcommand, covering listing, getting, setting, and resetting module configuration keys. The `--reset` flag resets all keys, a group, or one key. ```bash psc config [core|menu|context] # list all keys in a group psc config # get value psc config # set value psc config --reset # reset all keys to defaults psc config --reset # reset all keys in a group psc config --reset # reset one key ``` -------------------------------- ### Import PSCompletions module in PowerShell Source: https://github.com/abgox/pscompletions/blob/main/README.md Imports the PSCompletions module directly in PowerShell to load it for the current session. ```powershell Import-Module PSCompletions ``` -------------------------------- ### psc completion command usage Source: https://github.com/abgox/pscompletions/blob/main/design/psc-cli.md Shows the CLI syntax for the `completion` subcommand, covering listing, getting, setting, and resetting per-completion special configuration. The `--reset` flag resets all completions, one completion, or one key; surplus args are rejected. ```bash psc completion # completions with non-default special config psc completion # that completion's special config psc completion # get value psc completion # set value psc completion --reset # reset all completions' special config psc completion --reset # reset one completion's special config psc completion --reset # reset one key (exactly one; surplus args are rejected) ``` -------------------------------- ### psc list — list installed completions Source: https://github.com/abgox/pscompletions/blob/main/design/psc-cli.md Lists completions recorded in settings.alias with their trigger aliases. Output is text by default; --json returns {"completions": [{name, alias}]}. The PS wrapper forwards the CLI's text. ```bash psc list ``` -------------------------------- ### Install @jirutka/ajv-cli globally Source: https://github.com/abgox/pscompletions/blob/main/authoring/tooling.md Required before running validate-completion.ps1; the script throws with this command when ajv is not on PATH. ```bash npm install --global @jirutka/ajv-cli ``` -------------------------------- ### psc alias — manage trigger aliases Source: https://github.com/abgox/pscompletions/blob/main/design/psc-cli.md Lists all trigger aliases with no arguments, adds or removes aliases for a single installed completion, or restores every completion's aliases with --reset. Trigger aliases only open the completion menu; they do not create execution aliases. Validation rejects wildcards and the reserved name 'PSCompletions'. Claim order decides ownership: the last claim wins, and declarations (install, alias add, --reset) move a completion to the end of the order. ```text psc alias # list all trigger aliases ``` ```text psc alias add ... ``` ```text psc alias rm ... ``` ```text psc alias --reset # restore every completion's aliases ``` -------------------------------- ### psc update Source: https://github.com/abgox/pscompletions/blob/main/design/psc-cli.md Updates installed completions. With no arguments it performs a real-time library check; with names it re-downloads those completions unconditionally; with --old it updates only out-of-date completions; with --all it updates every installed completion found in the remote index. ```APIDOC ## [CLI] psc update ### Description Updates installed completions. With no arguments it performs a real-time library check; with names it re-downloads those completions unconditionally; with --old it updates only out-of-date completions; with --all it updates every installed completion found in the remote index. ### Usage ``` psc update psc update ... psc update --old psc update --all ``` ### Parameters #### Arguments - **name** (string) - Optional - Name of a completion to update. Naming a completion is the intent to update it; also used to repair corrupted or manually-removed files. A name that exists only in the remote index is installed by naming it. #### Flags - **--old** (flag) - Optional - Update only the out-of-date completions. - **--all** (flag) - Optional - Update every installed completion that exists in the remote completions.json index. Wins over --old when both are passed. - **--json** (flag) - Optional - Output results in JSON format. ### Behavior - Always downloads the index first. - A completion is "out of date" when its local .update differs from the remote version (symlinked completions are skipped). - Settings are patched, never overwritten: missing/empty trigger entries are filled from remote defaults, per-completion config only fills missing keys, and trigger customizations survive. - Any non-flag token counts as a name (e.g., `update --foo` targets a completion literally named `--foo`). - A mode flag wins over a name: `--all ` re-fetches everything, the name included; `--old ` follows the out-of-date set, saying so when that set is empty. A name the flag's set cannot cover (e.g., `--all `) is not installed by the run. - No-arg = real-time check: writes temp/change.json and reports the library status (out-of-date completions + newly added/removed/renamed completions), mirroring the startup notification. - After any successful update, the remaining out-of-date names are written back to temp/change.json so the next startup does not re-report them. ### Errors - Name not installed and not in the remote list: `: is not an available completion.` - Installed but not in the remote list: `: is not in the completion library.` (code `not_in_library`) - Download failure: `error: ` - Same `id` refusal as `add` (nothing lands on failure). ### Output - With `--json`: `data.completions` carries `{name, ok, error?}` per name (a migrated rename adds `renamed_from`); the no-argument check answers the four library-change lists (`update` / `added` / `removed` / `renamed`) instead. - Plain text otherwise. An empty result set prints `All completions are up to date.` in text mode. - A failed item fails the run: exit 1. - A locally-linked completion is reported (`ok: false`, code `not_updated`) but does not fail the run. ### PS wrapper Forwards `--all` / `--old` / the named arguments with `--json`, then renders `info.update.done` per successful result (migrated renames show `old -> new` in the name line), red errors for failures. ``` -------------------------------- ### Item (menu candidate, menu-mode input) Source: https://github.com/abgox/pscompletions/blob/main/design/protocol.md JSON object for a menu candidate provided by the host. Fields include `completion_text`, `list_item_text`, `symbol`, `tip`, `usage`, `example`, and `result_type`. `symbol` is pre-mapped by the host; `nospace` controls trailing space on apply. ```json { "completion_text": "add", "list_item_text": "add", "symbol": "~", "tip": "Add files", "usage": "add ", "example": null, "result_type": null } ``` -------------------------------- ### psc --self-update [--json] usage Source: https://github.com/abgox/pscompletions/blob/main/design/psc-cli.md Root-level flag that reports or performs self-update. Use --json for machine-readable output. A script install updates itself; other methods print the update command. ```text psc --self-update [--json] ``` -------------------------------- ### ajv validation error output on stdout Source: https://github.com/abgox/pscompletions/blob/main/authoring/tooling.md Example error line printed to stdout by ajv when validation fails; shows instance path and failing schema rule. ```text next[35].next[0].option[3].tip[0]: must not be empty [#/allOf/1/items/minLength] ``` -------------------------------- ### psc.trim(text, opts?) Source: https://github.com/abgox/pscompletions/blob/main/design/hooks.md Trims characters from a string. Whitespace is trimmed by default; `opts.chars` (a string whose characters form the trim set) overrides it (an empty string trims nothing). `opts.mode` is `"start"`/`"end"`/`"both"` (default `"both"`). ```APIDOC ## psc.trim(text, opts?) ### Description Trim characters; whitespace by default, `opts.chars` (a string whose characters form the trim set) overrides it (an empty string trims nothing). `opts.mode` is `"start"`/`"end"`/`"both"` (default `"both"`). ### Method Function call ### Parameters - **text** (string) - Required - The string to trim. - **opts** (table) - Optional - Options table. - **chars** (string) - Optional - A string whose characters form the trim set. Default is whitespace. - **mode** (string) - Optional - Trim mode: `"start"`, `"end"`, or `"both"`. Default is `"both"`. ### Returns - **string** - The trimmed string. ``` -------------------------------- ### Minimal input JSON for psc-menu build mode Source: https://github.com/abgox/pscompletions/blob/main/design/e2e-testing.md Hand-written input file for `psc-menu --result ` with empty `items` and a `build` context. The `manifest` must point to a language file whose hook is located by replacing `/language/.json` with `/hooks.lua`; `dir.cache: ""` disables the 10-second result cache so every run rebuilds. ```json { "items": [], "build": { "cmd": "t", "arg_tokens": ["help", ""], "treat_last_as_complete": false, "manifest": "/tmp/psc-e2e/t/language/en-US.json", "hooks": true, "cwd": "/tmp/psc-e2e/t", "config": {}, "global_config": {}, "data": {}, "dir": { "completions": "/tmp/psc-e2e/completions", "cache": "", "log": "/tmp/psc-e2e/log" }, }, "config": { "flags": {} }, "terminal": { "cursor": { "x": 0, "y": 5 }, "buffer": { "w": 120, "h": 30 }, "platform": "linux" } } ``` -------------------------------- ### Run Windows shim executables via shell with psc.run Source: https://github.com/abgox/pscompletions/blob/main/design/hooks.md On Windows, batch/powerShell shims (e.g. scoop's extension-less wrapper) cannot be spawned directly by psc.run. Use shell = true to run them through the shell, or wrap manually with cmd /c for precise control. Prefer psc.which first when in doubt. ```lua psc.run({ "scoop", "config" }, { shell = true }) ``` -------------------------------- ### Launch, wait, kill, and read back psc-menu artifacts Source: https://github.com/abgox/pscompletions/blob/main/design/e2e-testing.md PowerShell script to run the interactive menu detached, let the build finish, kill it, and read the rewritten input file, result file, and debug log. Do not redirect with `> $null 2>&1` on the `Start-Process` line because it nulls the `-PassThru` handle and breaks the later `Stop-Process`; use the `-Redirect*` file arguments instead. ```powershell $bin = "./module/PSCompletions/bin/-/psc-menu" # e.g. linux-x64 $proc = Start-Process -PassThru -NoNewWindow -FilePath $bin ` -ArgumentList "/tmp/psc-e2e/in.json", "--result", "/tmp/psc-e2e/out.json" ` -RedirectStandardError /tmp/psc-e2e/stderr.txt -RedirectStandardOutput /tmp/psc-e2e/stdout.txt Start-Sleep -Seconds 3 if (-not $proc.HasExited) { Stop-Process -Id $proc.Id -Force } Start-Sleep -Seconds 1 # let the background order thread flush its files (Get-Content /tmp/psc-e2e/in.json -Raw | ConvertFrom-Json).items | ForEach-Object { $_.completion_text } Get-Content /tmp/psc-e2e/out.json -ErrorAction SilentlyContinue Get-Content /tmp/psc-e2e/log/debug.log -ErrorAction SilentlyContinue ``` -------------------------------- ### Declarative registration with psc.on and psc.run Source: https://github.com/abgox/pscompletions/blob/main/design/hooks.md Recommended pattern: registrations run only when the location matches. Use psc.run to execute a command and iterate over its output lines, adding each as a completion item. ```lua psc.on({ command = "exec" }, function() for _, line in ipairs(psc.run({ "tool", "list" }) or {}) do psc.add({ name = line }) end end) ``` -------------------------------- ### Generate scaffold: ./scripts/create-completion.ps1 Source: https://github.com/abgox/pscompletions/blob/main/AGENTS.md Run this script to scaffold a new completion for the given command. Replace with the actual command name. ```powershell ./scripts/create-completion.ps1 ``` -------------------------------- ### psc rm Source: https://github.com/abgox/pscompletions/blob/main/design/psc-cli.md Removes installed completions by name or all except psc itself. Handles symlink/junction links as links only and validates names before any filesystem access. ```APIDOC ## [DELETE] psc rm ### Description Removes the named completions, or all installed completions except `psc` when `--all` is used. Each removal drops the entry from `settings.alias` and `config.completion`, removes the name from notification lists in `temp/change.json`, and deletes the completion entry from disk. Symlink/junction links are removed as links only, leaving the linked local source intact. ### Method DELETE ### Endpoint `psc rm ...` ### Parameters #### Path Parameters - **name** (string) - Required - One or more completion names to remove. Must be a single path-free token (no `/`, `\`, `:`, spaces, or control characters; not `.`, `..`, or empty). #### Query Parameters - **--all** (flag) - Optional - Removes every installed completion except `psc` itself. Absorbs co-args (extras are ignored). ### Request Example ``` psc rm mycompletion ``` ### Response #### Success Response (200) - **data.completions** (array) - When `--json` is used, each item contains `{name, ok, error?}`. - **info.rm.done** (string) - PS wrapper renders this per removed completion. #### Response Example ```json {"data": {"completions": [{"name": "mycompletion", "ok": true}]}} ``` ### Error Handling - No args → `Too few parameters.` - Name not in registry or remote library → `: is not an available completion.` - Name in remote library but not installed → `: Completion not added.` - Invalid name → `: is not an available completion.` (validated before filesystem access) - A failed item fails the run with exit code `1`. ``` -------------------------------- ### Create minimal fixture and hook for E2E testing Source: https://github.com/abgox/pscompletions/blob/main/design/e2e-testing.md Sets up a temporary directory with a minimal language manifest and a Lua hook that logs the tokens seen by the hook. Use this to isolate psc.log output from repo noise. The hook uses psc.on and psc.log; run luac -p on any hook before testing because a syntax error fails silently at runtime. ```powershell New-Item -ItemType Directory -Force /tmp/psc-e2e/t/language | Out-Null Set-Content /tmp/psc-e2e/t/language/en-US.json '{ "next": [ { "name": "help" }, { "name": "cache", "next": [ { "name": "clear" } ] } ] }' Set-Content /tmp/psc-e2e/t/hooks.lua 'psc.on({ command = "help" }, function() psc.log(psc.tokens) end)' ``` -------------------------------- ### Traversal steps for collecting help from all subcommands Source: https://github.com/abgox/pscompletions/blob/main/authoring/collecting-info.md Outlines the recursive process of running ` --help` at every level to collect options and subcommands. Emphasizes checking each subcommand for its own subcommands and recording all options at every level. ```text 1. Run: --help → lists all top-level subcommands 2. For EACH subcommand: Run: --help → check whether it has its own subcommands (look for a Commands section) 3. If it does, repeat for each of those: Run: --help 4. Record ALL options at every level ``` -------------------------------- ### Subcommand probe: run --help and grep for commands section Source: https://github.com/abgox/pscompletions/blob/main/AGENTS.md Run for every command to 2 levels. Output present means the manifest must have non-empty 'next'; output absent while 'next' exists proves nothing. The pattern is a sample, not the rule. ```bash --help | grep -E 'AVAILABLE COMMANDS|^Commands:' ``` -------------------------------- ### psc alias rm ... Source: https://github.com/abgox/pscompletions/blob/main/design/psc-cli.md Removes trigger aliases from a single installed completion. The name must be in `settings.alias`. This is a subtraction, not a declaration, and leaves the claim order alone. ```APIDOC ## [CLI] psc alias rm ... ### Description Removes trigger aliases from a single installed completion. The name must be in `settings.alias`. This is a subtraction, not a declaration, and leaves the claim order alone. ### Method CLI command ### Endpoint `psc alias rm ...` ### Parameters #### Arguments - **name** (string) - Required - The installed completion name. - **alias** (string) - Required - One or more trigger aliases to remove. ### Output - **JSON**: `{name, alias}`. ### Errors - Envelope `code`: `too_few_params` / `invalid_subcommand` / `not_installed`. - Per-alias codes: `alias_wildcard`, `alias_reserved`, `alias_not_found`. ### PS Wrapper Forwards the CLI's text. ``` -------------------------------- ### psc alias add ... Source: https://github.com/abgox/pscompletions/blob/main/design/psc-cli.md Adds trigger aliases to a single installed completion. Validates that aliases contain no wildcards and are not the reserved name `PSCompletions`. The last claim wins for alias ownership. ```APIDOC ## [CLI] psc alias add ... ### Description Adds trigger aliases to a single installed completion. The name must be in `settings.alias`. Validation: no wildcards (`*`/`?`); the reserved name `PSCompletions` is rejected. Nothing else is rejected: a word another completion claims, and a word the completion already has, are both accepted. Claim order decides: the last claim wins. A declaration moves a completion to the end of that order, so re-declaring a word the completion already has is the explicit way to take it back from a later claim. ### Method CLI command ### Endpoint `psc alias add ...` ### Parameters #### Arguments - **name** (string) - Required - The installed completion name. - **alias** (string) - Required - One or more trigger aliases to add. ### Output - **JSON**: `{name, alias, rejected}` where each rejected word carries `{alias, error: {code, message}}`. ### Errors - Envelope `code`: `too_few_params` / `invalid_subcommand` / `not_installed`. - Per-alias codes: `alias_wildcard`, `alias_reserved`, `alias_not_found`. ### PS Wrapper Forwards the CLI's text. ``` -------------------------------- ### TODO.md session record template Source: https://github.com/abgox/pscompletions/blob/main/authoring/working-files.md Template for the per-task session record file. It captures the goal, phase checklist, next step as an executable command or file path, open questions, and a session log. The next step must be exact and resumable, not vague like "continue the tool". This file is working material, never committed, and deleted only with the WIP directory on operator confirmation. ```markdown # — session record Goal: maintain and derive guide lessons. Source: `help/` (version), binary installed: yes/no. ## Phases - [x] preflight - [ ] collect ... ## Next Run: `python3 WIP//compare.py` Then: rebuild `en-US.json` from `source.json`. ## Open - ... ## Session log - 2026-10-01: collected all pages; coverage 0 missing. ``` -------------------------------- ### Deploy binaries with build-release.ps1 Source: https://github.com/abgox/pscompletions/blob/main/design/e2e-testing.md Run from the repository root to release-build the core workspace and copy psc-menu and psc into the module directory. Defaults to the host platform/arch and stops a same-path running process to release the file lock. ```powershell pwsh -NoProfile -File scripts/build-release.ps1 ``` -------------------------------- ### psc.run(argv, opts?) Source: https://github.com/abgox/pscompletions/blob/main/design/hooks.md Runs a command and returns stdout as an array of lines, or nil on failure or timeout. Supports options for timeout, working directory, output format, shell execution, environment variables, and capturing extra file descriptors. ```APIDOC ## psc.run(argv, opts?) ### Description Runs a command and returns stdout as an array of lines, or nil on failure or timeout. Supports options for timeout, working directory, output format, shell execution, environment variables, and capturing extra file descriptors. ### Parameters - **argv** (string[]|string) - Required - Command to run. - **opts** (table) - Optional - Options: - **timeout** (number) - Optional - Timeout in milliseconds (default 5000). - **cwd** (string) - Optional - Working directory. - **format** (string) - Optional - Output format: "json", "toml", or "yaml". Parses stdout and returns the parsed table, nil when unparseable. - **shell** (boolean) - Optional - Run through the system shell (cmd /c on Windows, sh -c elsewhere). - **env** (table) - Optional - Key-value pairs injected into the child process environment, merged with inherited env. - **capture_fd** (integer) - Optional - Captures an extra file descriptor (e.g., 8 for Python argcomplete), redirected to stdout via 8>&1. ### Returns - **string[]|table|nil** - stdout as an array of lines, parsed table if format is specified, or nil on failure/timeout. ``` -------------------------------- ### Correct and incorrect psc.run usage with format=json Source: https://github.com/abgox/pscompletions/blob/main/design/hooks.md Shows the recommended pattern for running a command with JSON output and iterating over the result, contrasted with a wrong approach that hides command failures. The wrong version treats a nil from format=json as an empty result, which can mask authentication or repository errors. ```lua -- right local data = psc.run({ "gh", "pr", "list", "--json", "number,title" }, { format = "json" }) or {} for _, pr in ipairs(data) do ... end -- wrong: a nil from format=json means the command itself failed -- no auth, no -- such repository, a field this build does not know -- and the retry returns -- nothing either, while hiding the reason. An empty menu says less than a -- command that visibly failed. if data then ... return end for _, line in ipairs(psc.run({ "gh", "pr", "list" }) or {}) do ... end ``` -------------------------------- ### Config (menu options) Source: https://github.com/abgox/pscompletions/blob/main/design/protocol.md JSON object for menu options. Includes `filter_hint`, `flags` (with `enable_list_loop`, `filter_mode`, `enable_apply_when_single`, `enable_apply_when_no_match`, `show_mode`), `context_switch`, `context_stay`, and `raw_config` for tip toggles. `show_mode` accepts `auto`, `inline-follow`, `altscreen-follow`, `altscreen-top`, `altscreen-bottom`. ```json { "filter_hint": "", "filter_hint_stale": "", "flags": { "enable_list_loop": true, "filter_mode": "wildcard", "enable_apply_when_single": false, "enable_apply_when_no_match": false, "show_mode": "auto" }, "context_switch": "~", "context_stay": "?", "raw_config": { "completion": { "enable_tip": 1 }, "global": {}, "default": { "enable_tip_usage": 1 } } } ``` -------------------------------- ### Run validate-completion gate: ./scripts/validate-completion.ps1 Source: https://github.com/abgox/pscompletions/blob/main/AGENTS.md Second gate to run on en-US.json. Must be clean before translation. ```powershell ./scripts/validate-completion.ps1 ``` -------------------------------- ### CLI error messages for flag deletion evidence Source: https://github.com/abgox/pscompletions/blob/main/authoring/maintenance.md Run the flag with no value to get the CLI's error text. The result determines whether to delete the option: 'unknown argument' or 'unexpected argument' means delete; 'a value is required' means keep. ```text unknown argument '--x' ``` ```text a value is required for '--x ' ``` ```text unexpected argument '--x' found ``` -------------------------------- ### psc.log usage examples Source: https://github.com/abgox/pscompletions/blob/main/design/hooks.md psc.log is a development-time logging function that appends formatted dumps of its arguments to debug.log in the host-provided log_dir (data/temp/log/). It accepts any number of arguments and prints each value on a separate line, including multi-return values. The function is marked @deprecated in types/psc.lua to remind developers to remove calls before shipping. ```lua psc.log(branches) -- data/temp/log/debug.log ``` ```lua psc.log(fn()) -- every returned value, one per line ``` -------------------------------- ### Declarative psc.on with command, option, and root anchors Source: https://github.com/abgox/pscompletions/blob/main/design/hooks.md Shows the core declarative pattern: each dynamic location owns its own psc.on handler. No explicit return is needed; nil yields a live list. ```lua -- command-chain anchor psc.on({ command = "exec" }, function() psc.add(psc.items(psc.run({ "tool", "list" }) or {})) end) -- option-value anchor psc.on({ option = "--arch" }, function() psc.add({ name = "x86_64" }) end) -- root psc.on({}, function() psc.add({ name = "bin" }) end) ``` -------------------------------- ### Generated scaffold for completions// Source: https://github.com/abgox/pscompletions/blob/main/authoring/manifest.md Shows the directory structure and files generated by ./scripts/create-completion.ps1 . The config.json contains an id and language array; language files are templates that need a full rewrite. ```text completions// ├── config.json # { "id": "", "language": ["en-US", "zh-CN"] } └── language/ ├── en-US.json # template content, needs a full rewrite └── zh-CN.json # template content, needs a full rewrite ``` -------------------------------- ### Probe subcommands with --help and grep Source: https://github.com/abgox/pscompletions/blob/main/authoring/collecting-info.md Runs a command's subcommand help and greps for a section listing commands. The pattern is a sample, not a rule; some tools use different section labels like 'CORE COMMANDS' or 'Sub-commands:'. ```bash --help | grep -Ei 'commands?\s*$' ``` -------------------------------- ### psc.on Source: https://github.com/abgox/pscompletions/blob/main/design/hooks.md Registers a completion hook for a command or option target. The hook is zero-arg and manipulates candidates via psc.add or direct completions operations. Registration runs at most once per build and handlers run sequentially. ```APIDOC ## psc.on ### Description Registers a completion hook for a command or option target. The hook is zero-arg and manipulates candidates via `psc.add` or direct `completions` operations. Registration runs at most once per build and handlers run sequentially. ### Parameters - **spec** (table) - Required - A table with keys `command` or `option` (or both for AND specs). `command` segments must be strings, empty array rejected (omit to target root), `""` is wildcard. `option` segments must start with `-` (or be `""` wildcards), empty array rejected. `multiple` (boolean) - Optional - Indicates the arity of one slot: after the first value is filled, the same location accepts another. - **handler** (function) - Required - Zero-arg function that manipulates candidates via `psc.add` or direct `completions` operations. ### Behavior - Validation failures are logged to `error.log` and registration becomes inert (never a process fault). - Unknown spec keys raise; unknown targets raise (aliases accepted). - For AND specs (`command`+`option`) either unknown side makes the whole spec inert (logged); single-key unknown still raises. - `psc.on` inside a handler is a recursion error. - Errors in handlers are logged, partial mutations persist, siblings unaffected. ### Example ```lua -- Each -include is a separate occurrence; no multiple. psc.on({ option = "-include" }, add_profiles) -- One occurrence carries a chain of values. psc.on({ option = "--cmd", multiple = true }, add_chain) -- One command occurrence takes any number of names. psc.on({ command = "install", multiple = true }, add_packages) ``` ``` -------------------------------- ### Sanity-check binary with psc-menu --self-test Source: https://github.com/abgox/pscompletions/blob/main/design/e2e-testing.md Parses a bundled sample, builds state, and exercises filters and layout without touching a terminal. 'self-test ok' means the binary is healthy. ```powershell ./module/PSCompletions/bin/-/psc-menu --self-test ``` -------------------------------- ### Run compare-json gate: ./scripts/compare-json.ps1 Source: https://github.com/abgox/pscompletions/blob/main/AGENTS.md First gate to run on en-US.json. It never checks schema, so structural defects pass and surface only after translation. ```powershell ./scripts/compare-json.ps1 ``` -------------------------------- ### Compile hooks.lua: luac -p Source: https://github.com/abgox/pscompletions/blob/main/AGENTS.md Verify hooks.lua compiles without errors. Run after writing hooks.lua. ```lua luac -p ``` -------------------------------- ### psc.on with multiple specs for one producer Source: https://github.com/abgox/pscompletions/blob/main/design/hooks.md Shows the preferred way to register a producer for multiple targets: pass an array of specs to a single psc.on call instead of making separate calls. The comment explains why the grouping is needed. ```lua psc.on({{ option = "--a" }, { option = "--b" }}, add_files) ``` -------------------------------- ### psc.on with option, multiple, and command Source: https://github.com/abgox/pscompletions/blob/main/design/hooks.md Shows three psc.on registrations: a repeated option without multiple, an option with multiple=true for a chain of values, and a command with multiple=true for any number of names. Each handler is zero-arg and manipulates candidates via psc.add or completions ops. ```lua -- Each -include is a separate occurrence; no multiple. psc.on({ option = "-include" }, add_profiles) -- One occurrence carries a chain of values. psc.on({ option = "--cmd", multiple = true }, add_chain) -- One command occurrence takes any number of names. psc.on({ command = "install", multiple = true }, add_packages) ``` -------------------------------- ### Platform Guard for Windows-only Environment Variable (APPDATA) Source: https://github.com/abgox/pscompletions/blob/main/design/hooks.md Shows the wrong and right approaches for handling Windows-only environment variables in hooks. The wrong version uses APPDATA directly, which is empty on Linux and degrades to a relative path. The right version prefers HOME or USERPROFILE and only falls back to APPDATA on Windows with a non-empty check. ```lua -- wrong local cfg = psc.json(psc.path(psc.env("APPDATA") or "", "Claude", "settings.json")) ``` ```lua -- right local home = psc.env("HOME") or psc.env("USERPROFILE") or "" local cfg = psc.json(psc.path(home, ".claude", "settings.json")) if not cfg and psc.platform == "windows" then local appdata = psc.env("APPDATA") or "" if appdata ~= "" then cfg = psc.json(psc.path(appdata, "Claude", "settings.json")) end end ``` -------------------------------- ### psc.add Source: https://github.com/abgox/pscompletions/blob/main/design/hooks.md Adds a completion item with an optional localized tip. The tip accepts a localized table keyed by language code, with `en-US` as the required fallback key. ```APIDOC ## psc.add ### Description Adds a completion item with an optional localized tip. The tip accepts a localized table keyed by language code, with `en-US` as the required fallback key. ### Parameters - **item** (table) - Required - A table with fields: - `name` (string) - Required - The completion item name. - `tip` (table) - Optional - A localized table keyed by language code (e.g., `["en-US"]`, `["zh-CN"]`). The engine picks the entry matching the loaded manifest's language variant, falling back to `"en-US"`, then the first entry. ### Example ```lua psc.add({ name = "svc", tip = { ["en-US"] = "Windows service", ["zh-CN"] = "Windows 服务", }, }) ``` ``` -------------------------------- ### Single target registration without array wrapper Source: https://github.com/abgox/pscompletions/blob/main/design/hooks.md For a lone target, write the bare spec directly in psc.on. Do not wrap it in an extra array just for uniformity. ```lua psc.on({ option = "--netrc-file" }, add_netrc) ``` -------------------------------- ### OrderInfo (background order recompute) Source: https://github.com/abgox/pscompletions/blob/main/design/protocol.md JSON object for background order recompute. Contains `history` path, `aliases` list, and `path` for the per-command order output file. The command name is derived from `aliases`; there is no separate `cmd` field. ```json { "history": "", "aliases": ["git", "g"], "path": "" } ``` -------------------------------- ### Ground-truth verification probe for a child command Source: https://github.com/abgox/pscompletions/blob/main/authoring/collecting-info.md Run the CLI's child command with --help to verify whether a subcommand exists. If it prints the parent's help, the subcommand does not exist (a defect); if it prints the child's own help or argument docs, it exists or was a value all along. This is only half the verdict—check the dispatch table and handler before deleting, as a missing help page may just mean missing documentation. ```text --help prints the PARENT's help → that "subcommand" does not exist (defect) prints the child's own help / argument docs → it exists (or it was a value all along) ``` -------------------------------- ### Probe validation with --projects Source: https://github.com/abgox/pscompletions/blob/main/authoring/collecting-info.md Verify a probe is sound by submitting a value that must fail (no-such-module) and one that must succeed (child). If the negative control passes, the probe is wrong. ```text --projects no-such-module → fails (probe is sound) --projects child → succeeds ``` -------------------------------- ### Mount root table for help-style command Source: https://github.com/abgox/pscompletions/blob/main/design/hooks.md Mounts the root table for a help-style command whose slot takes the tool's own subcommands (e.g., dart help ). Avoids duplicating the command list, preventing edits in two places and two languages. ```lua psc.on({ command = "help" }, function() psc.add(psc.mount_items({ "next" })) end) ``` -------------------------------- ### psc.run_batch(cmds, opts?) Source: https://github.com/abgox/pscompletions/blob/main/design/hooks.md Runs multiple commands in parallel and returns results in input order. Accepts the same options as psc.run; a failed or unparseable command yields nil at its index. ```APIDOC ## psc.run_batch(cmds, opts?) ### Description Runs multiple commands in parallel and returns results in input order. Accepts the same options as psc.run; a failed or unparseable command yields nil at its index. ### Parameters - **cmds** (table) - Required - Array of commands to run. - **opts** (table) - Optional - Same options as psc.run. ### Returns - **table** - Results in input order; nil for failed/unparseable commands. ``` -------------------------------- ### Check hook targets: check-hook-targets.ps1 Source: https://github.com/abgox/pscompletions/blob/main/AGENTS.md Verify every psc.on target resolves. Run after hooks.lua compiles. ```powershell check-hook-targets.ps1 ```